简体   繁体   English

C ++中的FILE I / O引发错误

[英]FILE I/O in C++ throws an error

int main(array<System::String ^> ^args)
{

FILE* fp;
char str[1];
int x = 0;

fp = fopen("C:\\input.txt", "r");

do{
    x = fscanf(fp, "%s", str);

    if (x != -1)  // So that the last string is not printed twice
    {
        printf("%s ", str);
    }

  }while (x != -1);

return 0;

}

This program prints the correct output. 该程序打印正确的输出。 BUT after printing, it throws an error in windows saying "Program stopped working". 但是打印后,它将在窗口中显示“程序停止工作”错误。 Also IF there is no text in the notepad file ie if it is blank, then it shows no error. 同样,如果记事本文件中没有文本,即如果文本为空白,则表明没有错误。 Please explain! 请解释!

The trouble is that you have a char array of one byte that you are reading strings into. 麻烦在于,您有一个要读取字符串的1字节的char数组。 You need to use an array that will be large enough to hold your largest piece of data. 您需要使用足够大的数组来容纳最大的数据。

First off the statement of you main function looks very much like c++ not C. 首先,您对main函数的声明非常像c ++而不是C。

Secondly from the statement char str[1]; 其次,从语句char str[1]; your declaring an array of characters that is of size 1. This means we can store 1 character inside this array so if we were to have char str[128]; 您声明一个大小为1的字符数组。这意味着我们可以在该数组中存储1个字符,因此,如果要使用char str[128]; we could store 128 chars in it (Dont forget about the \\0). 我们可以在其中存储128个字符(不要忘记\\ 0)。

So this program is trying to read a string into your character array but after the first letter of the string it has no place to store the rest of the string which is why it crashes 因此,该程序尝试将字符串读取到您的字符数组中,但是在字符串的第一个字母之后,它没有位置存储其余的字符串,这就是它崩溃的原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM