从文件中读取行 - 删除多余的空格
Reading lines from a file -- removing extra spaces
我正在使用ifstream
从文件中获取行并将它们存储为字符串。每行包含一个没有空格的单词。
virtual void readFromFile(char* input){
ifstream inf(input);
if(!inf){
cerr << "The specified file could not be found." << endl;
}
while(inf){
string str;
getline(inf, str);
pushFront(str); // store it in my data structure
}
inf.close();
}
文件.txt
a <= returns length 1 (correct)
at <= returns length 3
ate <= returns length 4
rate <= returns length 5
irate <= returns length 6
当我对对应于文件的第一个字符串调用 length()
时,它会返回正确的值。但是,对对应于所有其他行的字符串调用 length
会导致偏移量为 +1。例如,如果字符串的长度实际上是 5,则返回 6。这与新线路有关吗?如果是这样,如何从文件正确提取这些单词?
您使用 vi 作为文本编辑器,因此您可以通过执行 :set list
来显示不可见的字符。这将帮助您弄清楚您在大多数行中看到的这些附加字符可能是什么。
在 linux 中,通常的行尾是"\r",实际上是两个字符。我不完全确定getline
是否会省略它们。但是,作为预防措施,您可以添加以下逻辑:
getline(inf, str);
int len = str.size();
if (str[len - 1] == 'r') {
str.pop_back(); // not C++11 you do it str = str.erase(str.end() - 1);
}
pushFront(str); // store it in my data structure
如果定义了文本文件中的格式,则每行只包含一个单词,因此阅读此单词更容易且更确定。
void readFromFile(char* input){
ifstream inf(input);
if(!inf){
cerr << "The specified file could not be found." << endl;
}
for( string word; inf >> word; )
pushFront( word ); // store it in my data structure
} // inf.close() is done automaticly leaving the scope
相关文章:
- 将数组的地址分配给变量并删除
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C/C++编译器通常会删除重复的库吗
- 从链接列表c++中删除一个项目
- C++如何通过用户输入删除列表元素
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 使用函数"remove"删除重复元素
- 如何从多映射中删除特定的重复项
- 运算符C++ "delete []"仅删除 2 个前值
- 删除指向指针的指针是运行时错误吗
- 将指针设置为"nullptr"并不能防止双重删除?
- 为什么示例代码访问IUnknown中已删除的内存
- 从文件中读取行 - 删除多余的空格
- 从堆栈中删除多余的变量 - C++
- 删除多余的并行语句时的不同程序行为
- 以最小的开销删除多余的参数包参数
- 从字符串中删除多余空格的程序