Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Please help ... crashes strtok(), atoi, atof

Status
Not open for further replies.

giahan

Programmer
Sep 1, 2000
139
US
Please help ....
My program crashes with strtok() and atoi()
I read the line from data.txt file, convert the line to 4 variables (numbers), and store in an array.
Please help... thank you so much

---- My code -------

#include <fstream.h>
#include <iostream.h>
#include <string.h>
#include <cstdlib> // for exit function



int main()
{
char *str;
int data1[100], data4[100];
double data3[100], data2[100];

char *value;


int index=0;
fstream file_op("pro5a.txt");
while(!file_op.eof())
{
file_op.getline(str,100);
//cout <<str;

value = strtok (str, " ");
//cout <<str << endl;


data1[index]= atoi(value);

value = strtok (NULL, " ");
data2[index]= atof(value);

value = strtok (NULL, " ");
data3[index]= atof(value);

value = strtok (NULL, " ");
data4[index]= atoi(value);



cout << index << " "<< data1[index] << " " << data2[index] << " ";
cout << data3[index] << " " << data4[index] <<endl;


index ++;
}
file_op.clear();
file_op.close();
//cout <<endl;

return 0;
}

-----end code
-------data.txt-------
7500 150 62 1
5856 175.6598 82.55 2
7390 149.3679 75.7575 1
2689 200 73 2
5678 301 110 2





GH
 
Code:
char *str;
...
file_op.getline(str,100);
You didn't assign any memory to your str pointer (and didn't even initialize it) before passing it to getline(), so you're obviously going to crash.

BTW, it would be much better, easier & safer if you used all C++ instead of mixing C & C++. i.e. use std::string instead of char arrays & pointers, and use std::stringstream instead of strtok() & atoi()...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top