Read data from text file

May 7, 2013 at 4:51pm
The task is to read data from file.
sms.txt structure:
first line: hour minute phonenumber
second line: message

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
#include <vector>
#include <fstream>

using namespace std;

struct TSMS{
    int hour,minute,phonenumber;
    string message;
};

int main(){
    vector<TSMS> messages;
    TSMS puffer;
    ifstream in("sms.txt");
    if(in.is_open()){
        in >> puffer.hour >> puffer.minute >> puffer.phonenumber;
        cout << puffer.hour << ":" << puffer.minute << " @ " << puffer.phonenumber << endl;
        getline(in,puffer.message);
        cout << puffer.message << endl;
        in.close();
    }else cout << "404";
    return 0;
}


The problem is it does not read puffer.message. What do you think about it?
Last edited on May 7, 2013 at 4:52pm
May 7, 2013 at 5:06pm
Filestream before reading:
1
2
hour minute phonenumber
message

Filestream after Line 18:
1
2
//There is newline symbol
message

Line 20 reads whatever left from first line and discards newline (effectively reads empty string)
May 7, 2013 at 5:12pm
Thanks for your answer! I supposed it could be a "new line symbol" problem, but I can not solve it. What would you modify in code? Or should I read hour,minute,phonenumber with getline (if possible) also?
Last edited on May 7, 2013 at 5:13pm
May 7, 2013 at 5:17pm
1
2
3
#include <limits>
/*...*/
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Betweenline 18 and 20
Last edited on May 7, 2013 at 5:17pm
May 7, 2013 at 5:21pm
Please don't misunderstand me, thanks, but I would be greatful if there would be a friendlier solution... :)
May 7, 2013 at 5:30pm
This line skips all symbols before and with first encountered newline symbol.
You can use just std::cin.ignore(100, '\n'); if you can be sure that there won't be more than 99 whitespace characters at the end of first line.

If you want to rewrite program using getline, there is two ways:
a) Get the whole first string, assign it to the stringstream and get values from it
1
2
3
4
5
6
#include <sstream>
/*...*/
std::string temp;
std::getline(std::cin, temp);
std::istringstream x(temp);
x >> puffer.hour >> puffer.minute >> puffer.phonenumber;

b) Get every component separately and use stoi() like functions:
1
2
3
4
5
6
7
std::string temp;
std::getline(std::cin, temp, ' ');
puffer.hour = stoi(temp);
std::getline(std::cin, temp, ' ');
puffer.minute = stoi(temp);
std::getline(std::cin, temp);
puffer.phonenumber = stoi(temp);
But you should make sure that there wont be 2 whitespaces in a row.
May 7, 2013 at 8:54pm
Oh, I see what you did there... You deserve a trophy, sir, thanks!
Topic archived. No new replies allowed.