【问题标题】:C++ - How do I assign the data from a file to several variableC++ - 如何将文件中的数据分配给多个变量
【发布时间】:2015-02-04 14:27:00
【问题描述】:

我创建了一个 .txt 文件,其中包含产品名称、描述和数量的列表。 比如:

100 Plus , Sports Drink , 12 Sprite , Citrus Drink , 5 Dutch Lady, Milk, 8

我想将这些信息分配给三个变量,即string name、string description和int quantity

我尝试过使用while(product >> name >> description >> quantity) 之类的东西,但它只在它只包含单个单词且不包含逗号的情况下才有效,但不适用于包含多个单词的字符串。

这是我的代码。

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

using namespace std;

int main()
{
string name, description;
int quantity;
fstream product("product.txt");

string c_name[5],c_description[5];
int c_quantity[5];
int i=0;

while(product  >> name >> description >> quantity)
{

    cout<<i<<" Name= "<<name<<", Description= "<< description <<" , Quantity= " <<quantity<<"\n";
    c_name[i] = name;
    c_description[i] = description;
    c_quantity[i] = quantity;
    i++;
}

cout<<"-------------------------------------------------------------------"<<endl<<endl;

for(i=0;i<5;i++) //to display the variables
{
    cout<<i+1<<" "<<c_name[i]<<endl;
    cout<<i+1<<" "<<c_description[i]<<endl;
    cout<<i+1<<" "<<c_quantity[i]<<endl<<endl;
}

product.close();
return 0;
}

我可以知道我该怎么做吗? 如果可能的话,我只想坚持一些简单的头文件。 非常感谢。

【问题讨论】:

  • 您需要的是调用“解析”或“标记化”:读取一行,然后使用某种算法将其分解为您想要的部分。您的解析并不难,因为您的数据格式使用逗号作为分隔符,我建议您看看stackoverflow.com/questions/53849/…

标签: c++ file-io iostream formatted-input


【解决方案1】:

您不能使用流 &gt;&gt; 运算符,因为您发现它在第一个空格处停止。

你需要一次读一行

std::string line;
std::getline(product, line);

并使用std::string::find 查找逗号并使用std::string::substr 提取您需要的部分。

【讨论】:

    【解决方案2】:

    您可以考虑getline(),它允许使用分隔符:

    while ( getline(getline (product, name, ','), description, ',') >> quantity) 
    

    请注意,您可能必须删除description 和name 开头的空格,就像&gt;&gt; 之前所做的那样。或者,您也可以选择在循环块的末尾添加product.ignore(INT_MAX, '\n');,以确保在执行 nex getline 之前删除数量后面的最后一个换行符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-11
      • 2016-09-23
      • 1970-01-01
      相关资源
      最近更新 更多