c ++ чтение из файла с ':' между каждым словом - PullRequest
0 голосов
/ 21 апреля 2020

Как вы читаете файл в формате:

121:yes:no:334

Вот мой код:

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;
}

Вывод: 121yes0

Так что игнорирует секунгу линия, и 0 как-то найден.

Ответы [ 3 ]

0 голосов
/ 21 апреля 2020

Проблема в том, что после первого чтения поток выглядит следующим образом

:yes:no:334

, поэтому первый getline будет читать пустую строку перед ":", второй будет красным "да", и последнее целочисленное извлечение не удастся.

Используйте getline полностью и конвертируйте в целые числа по мере продвижения;

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;
}

(Обработка ошибок оставлена ​​как упражнение.)

0 голосов
/ 21 апреля 2020
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;}
0 голосов
/ 21 апреля 2020

Содержимое файла

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

, так что вы можете сделать что-то вроде

#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;
}
...