0

How do you read a file of the format:

121:yes:no:334

Here's my code:

int main(){

    string one, two;
    int three, four;

    ifstream infile;

    infile.open("lol.txt");

    infile >> three;

    getline(infile, one, ':');

    getline(infile, two, ':');

    infile >> four;

    cout << three << one << two << four;
    return 0;
}

output: 121yes0

So it ignores the secong get line, and a 0 is somehow found.

Giorgos Cut
  • 67
  • 1
  • 5
  • It's probably related to [this problem](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction). – molbdnilo Apr 21 '20 at 08:36
  • 1
    please explain the meaning of "none work", include expected and actual output in the qeustion – 463035818_is_not_an_ai Apr 21 '20 at 08:42
  • When working with iostreams one must either enable exceptions or manually inspect / adjust stream state after invoking each method. This code silently ignores all the possible failures. – user7860670 Apr 21 '20 at 08:56

3 Answers3

0

Contents of file

121:yes:no:334

infile >> three;           it would input 121
getline(infile, one, ':'); it did not take input due to :
getline(infile, two, ':'); it would take yes
infile >> four;            it take none

so you can do somethis like

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

using namespace std;

int main()
{

    string one, two;
    int three, four;

    ifstream infile;

    infile.open("lol.txt");

    infile >> three;

    infile.ignore();

    getline(infile, one, ':');

    getline(infile, two, ':');

    infile >> four;

    cout << three << one << two << four;

    return 0;
}
srilakshmikanthanp
  • 2,231
  • 1
  • 8
  • 25
0

The problem is that after the first read, the stream looks like this

:yes:no:334

so the first getline will read the empty string before ":", the second will red "yes", and the last integer extraction will fail.

Use getline all the way and convert to integers as you go;

int main(){
    string token;
    ifstream infile("lol.txt");
    getline(infile, token, ':');
    int three = std::stoi(token);
    string one;
    getline(infile, one, ':');
    string two;
    getline(infile, two, ':');
    getline(infile, token, ':');
    int four = std::stoi(token);
    cout << three << one << two << four;
    return 0;
}

(Error handling left as an exercise.)

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
0
int main(){
ifstream dataFile;
dataFile.open("file.txt");
int num1, num2;
dataFile >> num1; // read 121
dataFile.ignore(1, ':');
string yes, no;
getline(dataFile, yes, ':'); // read yes
getline(dataFile, no, ':'); // read no
dataFile >> num2; //read 334
return 0;}
Sina Raoufi
  • 54
  • 2
  • 6