繁体   English   中英

将字符串从文件中读入 1 个字符串,而不是 Integer c++

[英]Read strings into 1 string from file while not Integer c++

我有一个这样的文件:

 Dr Joe Hugh 180
 Grand Johnson 180

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

string str;

像这样:

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

并将号码放入:

int number;

我应该如何指示程序读取它们而不是 integer?

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

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

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;
    }
}

如果行总是以 integer 结尾,您可以在某些条件下使用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<vector<string>>而不是vector<string> ,并稍微更改循环以使其工作:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM