使用 c++ 读取文件时省略换行符
Omit the newline character in reading file with c++
我有这个代码:
#include <iostream>
#include <string>
#include <fstream>
int main()
{
std::ifstream path("test");
std::string separator(" ");
std::string line;
while (getline(path, line, *separator.c_str())) {
if (!line.empty() && *line.c_str() != 'n') {
std::cout << line << std::endl;
}
line.clear();
}
return 0;
}
文件"test"由数字填充,由不同数量的空格分隔。我只需要一个接一个地阅读数字,省略空格和换行符。此代码省略空格,但不省略换行符。
这些是输入文件"test"中的几行:
3 19 68 29 29 54 83 53
14 53 134 124 66 61 133 49
96 188 243 133 46 -81 -156 -85
我认为问题是这个*line.c_str() != 'n'
不是确定字符串是否line
命中换行符并且程序继续打印换行符的正确方法!
这个效果很好:
#include <iostream>
#include <string>
#include <fstream>
int main()
{
std::ifstream path("test");
std::string separator(" ");
std::string line;
while (getline(path, line, *separator.c_str())) {
std::string number;
path >> number;
std::cout << number << std::endl;
}
return 0;
}
使用流运算符>>
读取整数:
std::ifstream path("test");
int number;
while(path >> number)
std::cout << number << ", ";
std::cout << "ENDn";
return 0;
这将列出文件中的所有整数,假设它们用空格分隔。
getline
的正确用法是getline(path, line)
或getline(path, line, ' ')
其中最后一个参数可以是任何字符。
在这种情况下*separator.c_str()
转换为 ' '
.不建议使用此用法。
同样,*line.c_str()
指向line
中的第一个字符。查找最后一个字符使用
if (line.size())
cout << line[size()-1] << "n";
使用 getline(path, line)
时,line
将不包括最后n
字符。
这是另一个带有getline
的例子。我们逐行读取文件,然后将每行转换为 stringstream
,然后从每行读取整数:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
int main()
{
std::ifstream path("test");
std::string line;
while(getline(path, line))
{
std::stringstream ss(line);
int number;
while(ss >> number)
std::cout << number << ", ";
std::cout << "End of linen";
}
std::cout << "n";
return 0;
}
使用C++内置的 isdigit 函数。
相关文章:
- 如何防止clang格式在流运算符调用之间添加换行符<<
- C/C++ - 查询平台相关的换行符(用于内存映射文件)
- 使用 fgets() 从键盘读取时从以前的输入读取换行符
- 连接两个文件时如何避免冗余尾随换行符?
- 为什么 ifstream 文件中的换行符 - 当被此代码读取时 - 占用 2 个字节
- 在C++中输入时未检测到换行符
- 您如何做到这一点,以便在C++中读取文件时在文件末尾有换行符
- 使用 c++ 读取文件时省略换行符
- 读取文件内容时未定义的字符,文件末尾没有换行符
- 如何仅当字符串流包含任何换行符时才从字符串流中读取行
- 输出到文本文件时C++换行符
- 编写一个C++ pgm 以从文件"input.txt"读取,每当遇到句点时插入换行符并将修改的内容写入"output.txt"
- 在std::cout之后使用std::cin时,换行符从何而来
- 当使用字符串流解析字符串时,它会提取一个换行符
- 从文件读取数据时意外标记"换行符"附近出现语法错误
- 当子字符串只是一个换行符时,string.find(substring) 函数返回什么
- 使用boost::regex时,如何指定回车符和换行符匹配
- 如何在写入文本文件时向一行添加换行符
- 当我可以使用换行符时,为什么要使用endl ?
- 当文件有换行符时,ifstream::tellg在MSVC2012和gcc(mingw)上有所不同