如何从文本文件c中读取具有一定长度空格的输入字符串


How to read input string with spaces of certain length from text file c++

我的问题是我正在尝试从文本文件中输入char,string和int。我知道如何使用getline()输入,但是在使用get line()函数之后,不再有选项可以在字符串后输入其余整数。我的问题是,如何输入一个字符,然后是一个字符串(带空格),后跟3个整数?

data.txt看起来像这样

1
2
3
a   New York    5    7   9
b   Virginia    10   2   5
c   Los Angeles 25   15  6

这是我的代码:

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
27
28
29
30
31
32
33
34
35
36
37
   int main()
   {
    string city;
    double price;
    int amt1, amt2, amt3;
    char orderStatus;

    ifstream warehouse;
    ofstream output;
    warehouse.open("data.txt");
    output.open("dataOut.txt");

    while (warehouse.good())
    {
        warehouse >> orderStatus;
        output << orderStatus <<"\\t";

        getline(warehouse, city, '\\t');
        //warehouse >> city;
        output << city << endl;

        //warehouse >> amt1;
        //output << amt1 <<"\\t";

        //warehouse >> amt2;
        //output << amt2 <<"\\t";

        //warehouse >> amt3;
        //output << amt3;
    }


    warehouse.close();
    output.close();

    return 0;
   }

非常感谢您的帮助。


这是我对您的代码所做的修改。我添加了warehouse >> noskipws >> orderStatus >> skipws;来跳过第一个制表符分隔符。另外,在每次读取后添加if(!warehouse.good()) break;,以防数据不完整。如果是C,我会完成fscanf(file," %c %[^\\t]s %d %d %d", ...)

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    string city;
    double price;
    int amt1, amt2, amt3;
    char orderStatus;

    ifstream warehouse;
    ofstream output;
    warehouse.open("data.txt");
    output.open("dataOut.txt");

    while (warehouse.good())
    {
        warehouse >> orderStatus;
        if(!warehouse.good()) break;
        output << orderStatus <<"\\t";
        // to skip the tab delimiter
        warehouse >> noskipws >> orderStatus >> skipws;
        if(!warehouse.good()) break;

        getline(warehouse, city, '\\t');
        if(!warehouse.good()) break;
        output << city <<"\\t";

        warehouse >> amt1;
        if(!warehouse.good()) break;
        output << amt1 <<"\\t";

        warehouse >> amt2;
        if(!warehouse.good()) break;
        output << amt2 <<"\\t";

        warehouse >> amt3;
        if(!warehouse.good()) break;
        output << amt3 << endl;
    }


    warehouse.close();
    output.close();

    return 0;
}

一种快速的解决方案是使用atoi(指向文档的链接)。这听起来像是作业,所以我不想为您解决(这样做的乐趣在哪里?),但是您可以将值作为字符串输入。如果您愿意,也可以一次将一个字符手动转换为整数并重新构造数字,但是atoi可以全部处理。我猜它们是std :: string,所以您必须在它们上调用c_str(),因为atoi只接受C字符串。