0
Reading from a txt file
Here is my code snippet for reading data from a .txt file. https://code.sololearn.com/cLlcd3sKPYxj/?ref=app The file looks like this: K0.75 3.5 V1.3 4 2.4 V1.3 4 2.4 K0.75 3.5 , but my output does not match the file. What am I doing wrong?
1 Réponse
+ 1
You read characters from numbers into your "space" variable.
Add: cout << space << endl; after the first >> line.
You'll get this output which shows how numeric digits are read in:
space = 3
K0.75 0.5 0
space = 4
V1.3 2.4 1.3
space = 3
K0.75 0.5 0
space = 3
K0.75 0.5 0
Another difference is from how you print variable c even when you didn't read it from the file. That prints "0" when 0 didn't appear in the file.
Weird indentation doesn't directly change behaviour of your code but it hurts readability. Your if and else statements are mostly indented in a way that makes it harder to see what code applies to each case and could lead to some of the problems.
Here is an edited version of your code that prints the content of the file:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream data("data.txt");
if(!data) cout<<"Could not open a file";
else{
char letter,space;
double a=0,b=0,c=0;
for(;;){
data>>letter>>a>>b;
cout<<letter<<a<<" "<<b;
if(letter=='V')
{
data>>c;
cout <<" "<<c;
}
cout<<endl;
if(!data) break;
data.ignore(1000,'\n');
}
}
data.close();
return 0;
}