c++ - 如何从文本文件 C++ 中读取整数和特殊字符

标签 c++ text-files

我有这个 txt 文件:

{8500, X }
{8600, Y }
{8700, Z }
{8800, [ }
{8900, \ }
{9000, ] }
{9100, ^ }
{9200, _ }
{9300, ` }
{9400, a }
{9500, b }
{9600, c }

到目前为止,这是我的代码:

void file_reader(){

    std::ifstream file("1000Pairs.txt", ifstream::in);
    std::string str; 

    while (std::getline(file, str)){

        !isalpha(c); } ), str.end());
        str.erase(std::remove(str.begin(), str.end(), '{', ',', '}'), str.end());

        cout << str << endl;

        //int_reader(str, array);  // adds the integers to the array
    }       
    file.close(); 
}

给一个整数,在C++中如何返回对应的字符? 谢谢!!!

最佳答案

如上所述,通过尝试删除、迭代和类型检查每个字符是行,你正在使这比它需要的更难。如果您的格式如您所显示的那样 {num, c },那么您可以通过在 line 上使用 stringstream 来大大简化读取。这样你就可以只使用普通的 >>> 输入运算符和适当的类型来读取你想要的数据,并丢弃你不需要的字符,例如:

#include <sstream>
...
void file_reader(){
    int num;
    char c;
    ...
    while (std::getline(file, str)){
        char c1, c2;
        std::stringstream s (str);
        s >> c1;                // strip {
        s >> num;               // read num
        s >> c1 >> c2;          // strip ', '
        s >> c;                 // read wanted char
        /* you have 'num' and 'c' - test or map as needed */
        ...
    }
}

您可能需要根据自己的目的在这里或那里进行调整,但这种方法相当简单和可靠。 (从技术上讲,您可以在每次读取后检查流状态以检查 badbitfailbit,但我会把它留给您)

关于c++ - 如何从文本文件 C++ 中读取整数和特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50462208/

相关文章:

c++ - PacMan 广度优先搜索的实现

c++ - 为什么存储引用而不是请求两次我的应用程序要慢得多?

c++ - C++ 中安全异步回调的模式

c++ - 如何使用 C++ 或调用 winapi 查找字符是否属于特定代码页

java - Jar 在 FileOutputStream 中找不到 txt 文件

batch-file - 从文本文件中读取 - 批处理

javascript - 使用 HTML 和 Javascript 读取文本文件

c++ - 从 Stroustrup 的 C++ 编译模板友元示例时出现问题

c - 如何计算文本文件中相互重叠的单词

java - 将结果集中的值写入文本文件(.txt 文件)