【问题标题】:How to read the string into a file C++如何将字符串读入文件 C++
【发布时间】:2009-10-21 17:35:43
【问题描述】:

我在将字符串写入文件时遇到了一点问题, 如何将字符串写入文件并能够将其视为 ascii 文本? 因为当我为 str 设置默认值时我能够做到这一点,但当我输入 str 数据时却不行 谢谢。

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

int main()
{
    fstream out("G://Test.txt");

    if(!out) {
        cout << "Cannot open output file.\n";
        return 1;
    }
    char str[200];
    cout << "Enter Customers data seperate by tab\n";
    cin >> str;
    cin.ignore();
    out.write(str, strlen(str));
    out.seekp(0 ,ios::end);
    out.close();

    return 0;
}

【问题讨论】:

  • 只是一个旁注。有:char str[200];然后从输入中读取文本是一个坏主意。当有人输入超过 200 个字符时,您的程序将表现未定义并可能崩溃
  • std::string 可能设计得不好,但它是你的朋友。如果strstd::stringcin &gt;&gt; str 就可以正常工作。

标签: c++


【解决方案1】:

请使用std::string:

#include <string>

std::string str;
std::getline(cin, str);
cout << str;

我不确定您的具体问题是什么,但&gt;&gt; 只能读取到第一个分隔符(即空格); getline 将读取整行。

【讨论】:

  • 绝对值得注意的是,> 与字符串相比,与空白相关的行为不同。 +1
【解决方案2】:

请注意,>> 运算符将读取 1 个单词。

std::string   word;
std::cin >> word;  // reads one space seporated word.
                   // Ignores any initial space. Then read
                   // into 'word' all character upto (but not including)
                   // the first space character (the space is gone.

// Note. Space => White Space (' ', '\t', '\v'  etc...)

【讨论】:

    【解决方案3】:

    您在错误的抽象级别上工作。另外,关闭文件之前不需要seekp到文件末尾。

    您想读取一个字符串并写入一个字符串。正如 Pavel Minaev 所说,这是通过 std::stringstd::fstream 直接支持的:

    #include <iostream>
    #include <fstream>
    #include <string>
    
    int main()
    {
        std::ofstream out("G:\\Test.txt");
    
        if(!out) {
            std::cout << "Cannot open output file.\n";
            return 1;
        }
    
        std::cout << "Enter Customer's data seperated by tab\n";
        std::string buffer;
        std::getline(std::cin, buffer);
        out << buffer;
    
        return 0;
    }
    

    如果您想编写 C,请使用 C。否则,请利用您正在使用的语言。

    【讨论】:

    • 我会使用std::ofstream来写作。
    • 谢谢。已编辑。我出于习惯使用 fstream。
    【解决方案4】:

    我不敢相信没有人发现问题。问题是您在未以空字符终止的字符串上使用strlenstrlen 将继续迭代,直到找到零字节,并且可能返回不正确的字符串长度(或者程序可能崩溃 - 这是未定义的行为,谁知道?)。

    答案是对你的字符串进行零初始化:

    char str[200] = {0};
    

    提供您自己的字符串作为str 的值是可行的,因为这些内存中的字符串是以空值结尾的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-18
      • 2016-10-25
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 2010-09-15
      相关资源
      最近更新 更多