string,array,function parameter and ... problem | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

string,array,function parameter and ... problem

I writed a code and i run into some problems. I want to pass data to an array in a object that is has private access (Encapsulation) Problems : 1. 'string' has been not declared - L14 2. 'string' does not name a type - L22 3. 'name' was not declared in this scope - L15, L19 4. 'c' was not declared in this scope - L15 5. return-statement with a value, in function returning 'void' [-fpermissive] - L19 6. 'x' was not declared in this scope - L31 7. expected primary-expression before 'userInput' - L34 8. 'userInput' was not declared in this scope - L31 9. invalid conversion from 'const char*' to 'int' [-fpermissive] - L38 App used and Compiler : Code::Block GNU GCC Compiler Code link : https://code.sololearn.com/cXxKj3iM27cH/#cpp

23rd Nov 2018, 5:50 AM
Abolhasan Ashori
Abolhasan Ashori - avatar
2 Answers
+ 4
Remove #include <conio.h> ~~~ for (x = 0; ;x++) --> while (userInput != "exit") ~~~ variable declaration can't be chained with the input stream cin >> string userInput; Instead string userInput; cin >> userInput; ~~~ userInput = dataObj.setName(""); --> dataObj.setName(userInput); ~~~ c variable hasn't been defined in this scope. void setName(string inName) { Name[c] = inName; c++; } Probably should be a private member of Data class and it's better to be of type `size_t` or `unsigned`. ~~~ void getName(int n) { return Name[n]; } must be string getName(int n) { return Name[n]; } ~~~ Rudimentary solution for holding 100 name + exit sentinel string Name[]; --> string Name[100]; ~~~ Remove getch(); ~~~ #include <iostream> #include <string> using namespace std; class Data { public: Data() { c = 0; } void setName(string inName) { if (c >= 100) { cout << "Array is full\n"; return; } Name[c] = inName; c++; } string getName(int n) { if (n >= c) { cout << "Array bound violation\n"; return ""; } return Name[n]; } private: size_t c; string Name[100]; }; using namespace std; int main() { int n = 0; Data dataObj; string userInput = ""; while (userInput != "exit") { cout << "Import Your Name" << endl << endl; cout << "if you want to exit, type \"exit\"" << endl; cin >> userInput; dataObj.setName(userInput); ++n; } for (size_t i = 0; i <= n; ++i) cout << dataObj.getName(i) << endl; return 0; }
23rd Nov 2018, 7:06 AM
Babak
Babak - avatar
+ 2
Use std::string instead of string Or move using namespace std befor the class declaration
23rd Nov 2018, 6:01 AM
Taste
Taste - avatar