E
Eric Lilja
Hello, I have a text file with following format:
number one_word
string
number number char string
There may be several lines of the last type (number number char
string), the number of such lines should correspond to the first number
in the file. Anyway, how do I read such a file if I need the numbers
stored in ints, the single char stored in a char and the strings (words
or sentences) stored in a std::string? I tried:
static void
read_and_display_file(ifstream& file)
{
int num = 0;
string str;
/* We know the first line is a number and a single word. */
file >> num >> str;
cout << num << " " << str << endl;
/* We know the second line is a string (that contain spaces). */
getline(file, str);
cout << str << endl;
int a = 0;
int b = 0;
char c = '\0';
/* Now we loop the number of times as stated at the beginning of
the file. The line all have the following format:
int int char some_string_that_may_contain_spaces */
for(int i = 0; i < num; ++i)
{
/* First we read the two ints and the char. */
file >> a >> b >> c;
/* The we read the remainder of the line into a std::string. */
getline(file, str);
cout << a << " " << b << " " << c << " " << str << endl;
}
}
My testfile:
4 word
a sentence
1 2 a dld dld
3 4 b dlsl dlfefef
5 6 c slspod sejdjd
7 8 d lsll spd dslddd
The output when I run my testprogram:
$ ./foo.exe
4 word
0 0
0 0
0 0
0 0
Please help me solve this, thanks!
number one_word
string
number number char string
There may be several lines of the last type (number number char
string), the number of such lines should correspond to the first number
in the file. Anyway, how do I read such a file if I need the numbers
stored in ints, the single char stored in a char and the strings (words
or sentences) stored in a std::string? I tried:
static void
read_and_display_file(ifstream& file)
{
int num = 0;
string str;
/* We know the first line is a number and a single word. */
file >> num >> str;
cout << num << " " << str << endl;
/* We know the second line is a string (that contain spaces). */
getline(file, str);
cout << str << endl;
int a = 0;
int b = 0;
char c = '\0';
/* Now we loop the number of times as stated at the beginning of
the file. The line all have the following format:
int int char some_string_that_may_contain_spaces */
for(int i = 0; i < num; ++i)
{
/* First we read the two ints and the char. */
file >> a >> b >> c;
/* The we read the remainder of the line into a std::string. */
getline(file, str);
cout << a << " " << b << " " << c << " " << str << endl;
}
}
My testfile:
4 word
a sentence
1 2 a dld dld
3 4 b dlsl dlfefef
5 6 c slspod sejdjd
7 8 d lsll spd dslddd
The output when I run my testprogram:
$ ./foo.exe
4 word
0 0
0 0
0 0
0 0
Please help me solve this, thanks!