【发布时间】: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");
}
感谢您的关注。期待您的回复。
【问题讨论】:
-
在作为输入文件打开之前尝试关闭输出文件。