我如何扫描行并提取包含空格的整数和字符串

时间:2018-02-16 19:49:04

标签: c++ c++11

我有一个包含以下行的文件:

51:HD L80 Phone:78
22:Nokia Phone:91

我需要将它们分成3个单独的变量

(int, string, int)
int id = line[0]
string phoneName = line[1]
int price = line [2]

我尝试了许多解决方案,例如:

std::ifstream filein("records");

for (std::string line; std::getline(filein, line); )
{
    // std::cout << line << std::endl;

    std::istringstream iss (line);
    std::string word;

    std::vector<string> tempString;
    while(std::getline(iss,word,',')){
        tempString.push_back(word);
        // std::cout << word << "\n";
}

然而,在这个例子中,我确实得到了值,但它们是在一个流而不是一次性进入。我不想将它们保存到向量中(没有其他方法来存储传入的值),但在获取所有3个值后立即调用函数。

这是对已接受答案的修改:

`for (std::string line; std::getline(filein, line); )
{
// std::cout << line << std::endl;
std::istringstream iss (line);

for (int stockID; iss >> stockID; )
{
    char eater;
    iss >> eater; // this gets rid of the : after reading the first int
    std::string stockName;
    std::getline(iss, stockName, ':'); // reads to the next :, tosses it out and stores the rest in word
    std::string catagory;
    std::getline(iss, catagory, ':'); // reads to the next :, tosses it out and stores the rest in word
    std::string subCatagory;
    std::getline(iss, subCatagory, ':');
    int stockPrice;
    iss >> stockPrice;
    iss >> eater; // this gets rid of the : after reading the first int
    int stockQTY;
    iss >> stockQTY; // get the last int
    // iss >> eater;

    // std::cout << stockName << "\n";

    Record recordd = Record(stockID,stockName,catagory,subCatagory,stockPrice,stockQTY);
    record.push_back(recordd);
}   

}`

表示文本文件包含:

51:HD L80 Phone:Mobile:Samsung:480:40 22:Nokia Phone:Mobile:Nokia:380:200

2 个答案:

答案 0 :(得分:1)

如果您知道每行中只有3列,则没有理由在此使用std::stringstream。相反,您可以直接从文件中读取这些值,将它们存储在临时值中,然后使用这些临时变量调用该函数。

for (int a; filein >> a; )
{
    char eater;
    filein >> eater; // this gets rid of the : after reading the first int
    std::string word;
    std::getline(filein, word, ':'); // reads to the next :, tosses it out and stores the rest in word
    int b;
    filein >> b; // get the last int
    function_to_call(a, word, b);
}

答案 1 :(得分:-1)

您可以在此处找到分割字符串的不同方法:

https://www.fluentcpp.com/2017/04/21/how-to-split-a-string-in-c/

示例:

std::vector<std::string> split(const std::string& s, char delimiter)
{
   std::vector<std::string> tokens;
   std::string token;
   std::istringstream tokenStream(s);
   while (std::getline(tokenStream, token, delimiter))
   {
      tokens.push_back(token);
   }
   return tokens;
}