【问题标题】:Read strings into 1 string from file while not Integer c++将字符串从文件中读入 1 个字符串,而不是整数 c++
【发布时间】:2021-04-04 13:58:11
【问题描述】:

我有一个这样的文件:

 Dr Joe Hugh 180
 Grand Johnson 180

我想把名字读成一个字符串,但我不知道名字有多长:

string str;

像这样:

str = "Dr Joe Hugh"
or
str = "Grand Johnson"

并将号码放入:

int number;

如果不是整数,我应该如何指示程序读取它们?

我想过getline,但我不知道该怎么做

【问题讨论】:

  • 什么时候是str = "string1 string2 string3",什么时候是str = "string1 string2"
  • 数字是否总是输入字符串的最后一个空格分隔部分?
  • @leech 就像名字一样,当我不知道名字有多长时,我想将整个名字读入 1 str 中

标签: c++ string


【解决方案1】:

如果行总是以整数结尾,您可以使用带有某些条件的while 循环创建一个更简单的解决方案。

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

bool isNumber(std::string str)
{
    for (int i = 0; i < str.length(); i++)
    {
        if (!isdigit(str[i]) && str[i] != '-') return false;
    }
    return true;
}

int main() {
   std::vector <std::string> names;
   std::vector <int> numbers;
   std::string str;
   int a;
   std::fstream file;
   file.open("PATH", std::ios::in);
   if (!file) return -1;
   while (file >> str)
   {
       if (isNumber(str))
       {
           a = stoi(str);
           numbers.push_back(a);
       }
       else names.push_back(str);
   }
}

现在你已经准备好了两个包含数字和名称的向量。如果您希望names 成为行,而不仅仅是单词,请使用vector&lt;vector&lt;string&gt;&gt; 而不是vector&lt;string&gt;,并稍微更改循环以使其工作:)

【讨论】:

    【解决方案2】:

    如果数字总是在行尾并且总是以空格开头,你可以这样做:

    struct Line {
        std::string str;
        int number;
    };
    
    std::istream &operator>>(std::istream &in, Line &l) {
        if (std::getline(in, l.str)) {
            const char *last_space = l.str.c_str();
    
            for (const char &c : l.str)
                if (c == ' ')
                    last_space = &c;
    
            l.number = std::atoi(last_space);
            l.str = l.str.substr(0, last_space - l.str.c_str());
        }
    
        return in;
    }
    

    编辑 2:示例用法:

    int main() {
        std::ifstream f("/path/to/file.txt");
    
        std::vector<Line> lines;
    
        // reads every line from the file into the vector
        for (Line l; f >> l; lines.push_back(std::move(l))) {}
    
        // do stuff with your vector of lines
    }
    

    编辑:以牺牲可读性为代价,对上述代码的优化(如果字符串很长)将替换寻找最后一个空格的for循环,用一个反向循环字符串的循环。

    for (auto it = l.str.crbegin(); it != l.str.crend(); ++it) {
        if (*it == ' ') {
            last_space = &*it;
            break;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2020-09-21
      • 2013-01-16
      相关资源
      最近更新 更多