我的字符串从ifstream中得到的也"n"
My string gets from the ifstream also " "
这是我的问题:我从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();
。)
相关文章:
- 将 ifstream 读取到 char* 以进行 int 和字符串转换
- 将字符串参数传递给 ifstream
- 如何使用 istream_iterator 从 ifstream 中读取带有空格的字符串?
- 为什么当 ifstream 创建从键盘读取字符串的文件时出现错误
- C ++ ifstream 无法读取字符串,并且在读取字符时出错
- 从带有ifstream和get()的文件中获取一个用引号表示的字符串
- 如何使用ifstream c ++从带有换行符的文件读取字符串
- C 使用字符串作为打开文件路径的ifstream错误
- 使用套接字编程的c++中的字符串流与ifstream(ofstream)
- C++如何将ifstream内容(来自文件)分配给具有偏移量的字符串(istreambuf_editor)
- C++ 如何从 ifstream 和 getline() 获取子字符串
- 用于中断哈希字符串的 ifstream
- ifstream 获取从字符到字符串的行更改输出
- ifstream get string的字符串进入数组
- ifstream在文件中获取错误的字符串
- 如何使用ifstream C++读取子字符串
- 通过 std::ifstream 从字符串中获取每个值
- std::getline 用于 ifstream,使用参数字符串或 char *
- 使用字符串作为打开文件路径时出现ifstream错误
- ifstream gcount在getline字符串重载时返回0