c++ - c++读取文件省略换行符

标签 c++ string newline getline

我有这个代码:

#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 << "END\n";
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 line\n";
    }
    std::cout << "\n";
    return 0;
}

关于c++ - c++读取文件省略换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46799136/

相关文章:

c++ - 从 C++ 注册预关机通知的正确方法

c++ - 我什么时候可以打破别名规则?

javascript使用正则表达式在多个字段上分割字符串

html - URL 包含原始换行符的资源请求已弃用

c++ - C++编码样式

JavaScript 字符串编码/解码

string - 在 Oracle 10g 上创建聚合函数返回无用的错误

c - strcmp() 和文本文件中的换行符

python - 删除/替换多行字符串中的所有空格,换行符除外

c++ - 数组元素到可变参数模板参数