c++ - Can't make atoi take in a string (string vs. C-string?) -
i have read line file , trying convert int. reason atoi()
(convert string integer) won't accept std::string
argument (possibly issue strings vs c-strings vs char arrays?) - how atoi()
work right can parse text file? (going pulling lots of ints it).
code:
int main() { string line; // string filename = "data.txt"; // ifstream file(filename) ifstream file("data.txt"); while (file.good()) { getline(file, line); int columns = atoi(line); } file.close(); cout << "done" << endl; }
the line causing problems is:
int columns = atoi(line);
which gives error:
error: cannot convert
'std::string'
'const char*'
argument '1' 'intatop(const char*)
'
how make atoi work properly?
edit: all, works! new code:
int main() { string line; //string filename = "data.txt"; //ifstream file (filename) ifstream file ("data.txt"); while ( getline (file,line) ) { cout << line << endl; int columns = atoi(line.c_str()); cout << "columns: " << columns << endl; columns++; columns++; cout << "columns after adding: " << columns << endl; } file.close(); cout << "done" << endl; }
also wondering why string filename = "data.txt"; ifstream file (filename) fails, but
ifstream file("data.txt");
works? ( reading filename form command line need make not string literal)
the c_str method exists purpose.
int columns = atoi(line.c_str());
btw code should read
while (getline (file,line)) { ...
just because file 'good' not mean next getline succeed, last getline succeeded. use getline directly in while condition tell if did read line.
Comments
Post a Comment