我的字符串从ifstream中得到的也"n"

My string gets from the ifstream also " "

本文关键字:字符串 ifstream 我的      更新时间:2023-10-16

这是我的问题:我从txt中读取了一些行。这个txt是这样的:

Ciao: 2000
Kulo: 5000
Aereo: 7000

ecc。我必须将(":")之前的每个单词都分配给一个字符串,然后再分配给映射;将数字转换为int,然后转换为map。问题是,从第二行开始,我的字符串变成了("\nKulo")ecc!我不想要这个!我能做什么?

这是代码:

        #include <iostream>
        #include <fstream>
        #include <string>
        #include <map>
        using namespace std;
        int main()
        {
            map <string, int> record;
            string nome, input;
            int valore;
            ifstream file("punteggi.txt");
            while (file.good()) {
                getline(file, nome, ':');
        //        nome.erase(0,2); //Elimina lo spazio iniziale
                file >> valore;
                record[nome] = valore;
                cout << nome;
            }
            file.close();
            cout << "nNome: ";
            cin >> input;
            cout << input << ": " << record[input] << "n";
            cout << "nn";
            return 0;
        }

问题是std::getline()是一个未格式化的输入函数,因此不会跳过前导空格。从外观上看,您希望跳过前导空格:

while (std::getline(in >> std::ws, nome, ':') >> valore) {
    ...
}

或者,如果有前导空格,您可以在读取值后ignore()所有字符,直到行尾。

顺便说一句,因为我在这里看到有人建议使用std::endl:不要使用std::endl,除非你真的打算刷新缓冲区。这是写入文件时经常出现的主要性能问题。

使用标准的换行习惯用法:

for (std::string line; std::getline(file, line); )
{
    std::string key;
    int n;
    std::istringstream iss(line);
    if (!(iss >> key >> n) || key.back() != ':') { /* format error */ }
    m.insert(std::make_pair(std::string(key.cbegin(),  std::prev(key.cend()),
                            n));
}

(您也可以使用key.substr(0, key.length() - 1),而不是迭代器中的临时字符串,尽管我认为我的版本可能更高效。或者在将数据插入映射之前添加key.pop_back();。)