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' 'int atop(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

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -