【问题标题】:String doesn't want to store a 2700 character word字符串不想存储 2700 个字符的单词
【发布时间】:2021-08-19 11:16:33
【问题描述】:

我正在尝试制作一个程序来打印 100-999 之间的所有数字。之后,您可以选择要查找的数字。然后你输入数字的位置,它就会被输出。

有一个问题。名为 str 的字符串在数字 954 处停止存储。

代码如下:

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

int main()
{
    //Prints to myFile the numbers from 100 to 999 without a space in between. Like this: 100101102...999
    ofstream myFile("numere.txt");
    for(int i = 100; i <= 999; i++)
        myFile << i;
    //Makes the string str to store the line: 100101102103...999. But only stores until 954 (100101102..954)
    ifstream myFileRead("numere.txt");
    string str;
    while(getline(myFileRead, str))
        cout << str << endl;
    //Ouputs the lenght that should be 2700 but is instead 2565
    cout << endl;
    cout << "String legth: " << str.size() << endl;
    cout << endl;
    
    int n, k;
    cout << "Enter how many numbers do you want to find: ";
    cin >> n;

    for(int i = 1; i <= n; i++){
        cout << "Enter number position(it starts from 0) : ";
        cin >> k;
        cout << "Here's the number on position " << k << ": " << str.at(k);
        cout << endl;
    }

    system("pause>0");
}

感谢您的关注。期待您的回复。

【问题讨论】:

  • 在作为输入文件打开之前尝试关闭输出文件。

标签: c++ string


【解决方案1】:

C++ 流被缓冲。当您使用&lt;&lt; 写入文件时,它不会立即写入文件。

在阅读之前尝试关闭或刷新ofstream

  myFile.close(); // or...
  myFile.flush();

如需了解更多详情,请联系flush()close()


PS:实际上很少需要明确关闭fstream。当您使用单独的函数进行写入和读取时,您不需要这样做:

 void write_to_file() {
       std::ofstream myFile("numere.txt");
       //...
 }
 void read_from_file() {
       std::istream myFile("numere.txt");
       //...
 }

因为ofstream的析构函数已经关闭了文件。

【讨论】:

  • 主要是为了那个 PS,+1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-01
  • 2017-11-02
  • 2011-02-11
  • 2014-08-09
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
相关资源
最近更新 更多