1

I am relatively new to C++, so be gentle. I have a text-file I want to read, but when i read the file it skips the whitespace (space) between separated words.

I tried to take away as much junk-code as possible so it would be easier to read.

#include <iostream>
#include <string>
#include <sstream>
#include <fstream>

using namespace std;

int main(.....)
{
    ifstream in_file;
    string filename;
    string status;
    readStringToMem(in_file, status);

    cout << "Type in the filename :    ";
    getline(cin, filename);    
    in_file.open(filename);
    readStringToMem(in_file, status);
}

void readStringToMem(ifstream& in_file, string& string_value)
{
    string input_string;
    getline(in_file, input_string, '|');
    stringstream myInputStream(input_string);
    myInputStream >> string_value;
}

My file may look like this:

Status is ok | 100

But when I read it, it comes out like this:

Status 100

Thanks in advance! Any help will be great!

UpAndAdam
  • 4,515
  • 3
  • 28
  • 46

1 Answers1

2

You are trying too hard, this

void readStringToMem(ifstream& in_file, string& string_value)
{
    string input_string;
    getline(in_file, input_string, '|');
    stringstream myInputStream(input_string);
    myInputStream >> string_value;
}

should be this

void readStringToMem(ifstream& in_file, string& string_value)
{
    getline(in_file, string_value, '|');
}

Much simpler, in fact readStringToMem is so simple I wonder if it's worth putting into a separate function.

I think you were probably confused by the integer case. In that case you have to convert the string you have read with getline to an integer. And you would do that using stringstream. But in the string case you already have a string so there is no conversion to do and no need for stringstream.

john
  • 85,011
  • 4
  • 57
  • 81
  • Thank you. That worked like a charm. But another problem came up though. I have two strings that is to be read (string int string). Because of the last string it sort of skips a line when I am printing it to screen.: `_Status is ok 100 Print ok Status is ok 101 Print still ok_` Any suggestions hos to remove the skip-line-part? – user2292468 Apr 17 '13 at 21:40
  • 2
    @user2292468 Another problem, another question. – john Apr 17 '13 at 21:41
  • @user2292468 You're looking for this: [Ask Question](http://stackoverflow.com/questions/ask) – Drew Dormann Apr 17 '13 at 22:10
  • @DrewDormann Actually, they need to sit quietly and think, maybe search, read their documentation, textbooks, etc. Then strip down their code to a simple example, and try to find the essence of the problem. And read and search a bit more. And did I say reduce the code to its essence? Then maybe ask another question. – Peter Wood Apr 17 '13 at 22:29