Reputation: 837
i have a text file that has the numbers on one line like (no spaces between commas):
-1,5,-3,10,500000,-6000
so far this is the code i have but i am not getting anything back at all in the vector array
fstream fp;
vector<int> numbers;
int number;
fp.open("numbers.txt", ios::in | ios::binary);
if(fp.is_open()){
while(fp >> number){
numbers.push_back(number);
}
}
fp.close();
cout << "Numbers:\n";
for (int i=0; i < numbers.size(); i++) {
cout << numbers[i] << '\n';
}
i feel like im just not reading the file properly or the whole line is just getting put into the number var. Also, the number of numbers in the file is unknown so i would like to stay away from hardcoding it
Upvotes: 0
Views: 16753
Reputation: 86
fstream fp;
vector<int> numbers;
int number;
fp.open("numbers.txt", ios::in | ios::binary);
if(fp.is_open()){
while(fp >> number){
numbers.push_back(number);
fp.get();
}
}
fp.close();
cout << "Numbers:\n";
for (int i=0; i < numbers.size(); i++) {
cout << numbers[i] << '\n';
}
You just forgot about the comma's! use fp.get(); to get rid of them, and then it'll work fine :D
Upvotes: 4
Reputation: 87959
Like this
if(fp.is_open()){
while(fp >> number){
numbers.push_back(number);
char dummy_variable_for_the_comma;
fp >> dummy_variable_for_the_comma; // read and discard a comma
}
}
You have to tell the computer to skip the commas, it won't do that for you.
Upvotes: 0
Reputation: 96810
Your input fails when it trys to insert a ,
into an integer. You should use getline
to insert the values up until the comma delimiter:
while (std::getline(fp, number, ','))
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Upvotes: 1
Reputation: 5711
First of all, your input file is not binary - don't use ios::binary
.
Second of all, you need to split your input tokens. Your input operation will fail every time you stumble upon a comma. You might need to input a character or a string to deal with those.
Upvotes: 2