0

我有一个格式如下的文件:

Word1          num1 num2
Word2 Word3    num3 num4

Word1 和 num1 之间有 15 个空格,用于 Word1、Word2 和 Word3 等单词。

我想读取前 15 个字符并将它们放入一个字符串中,然后读取数字:

string[0] = "Word1          ";
number[0] = num1;
number[1] = num2;
string[1] = "Word2 Word3    ";
number[2] = num3;
number[3] = num4;
...

我目前用来从文件中读取数据的函数:

void read_data(){

ifstream datafile("U2.txt");

datafile>> product_count >> product2_count;

for (int i = 1; i <= product_count; i++) {
    datafile>> product_cost[i];
}

for (int i = 1; i <= product2_count; i++) {
    datafile>> products[i].product2_name;
    for (int j = 1; j <= product_count; j++) {
        datafile>> products[i].product_ammount[j];
    }
}

datafile.close();

}

和数据文件本身:

6 5
12 25 35 2 3 9
Salotos        5 1 0 0 2 1
Kepsnys        6 3 12 9 0 0
Gaiva          0 0 1 15 1 0
Ledai Miau     0 0 5 5 5 1
Tortas         1 2 1 1 1 1
4

2 回答 2

1

你的问题在于线路

datafile >> products[i].product2_name;

只能读取到第一个空格。您需要像 CharlesB 建议的那样阅读它,使用 提取前 15 个字符string::substr,然后进行修剪。看这里

我强烈怀疑你的for循环应该从 0 而不是 1 开始。

于 2012-05-14T12:12:51.433 回答
1

我不会为你写代码,但基本的想法是

  • getline()用to a读一行std::string
  • 取前 15 个字符,修剪它们以删除空间
  • std::stringstream用字符串的其余部分构建 a ,然后执行sstream >> num1[i] >> num2[i](其中numXint 数组和iline 的索引。
于 2012-05-14T11:41:56.890 回答