简体   繁体   English

infile 到一个字符数组,一次一个字符,没有字符串

[英]infile to a char array, one char at a time, NO STRINGS

在此处输入图像描述 I'm trying to get input from a file, but I need to do it one char at a time into a character array.我正在尝试从文件中获取输入,但我需要一次将一个字符输入字符数组。 There are no numbers or symbols, but it only prints out the first letter.没有数字或符号,但它只打印出第一个字母。

Your use of inFile.eof() is wrong .您对inFile.eof()的使用是错误的 Move the read operation into the loop condition instead.将读取操作移到循环条件中。 And, consider using inFile.get(...) instead of inFile >> ... in this situation.并且,考虑在这种情况下使用inFile.get(...)而不是inFile >> ...

But, more importantly, your code prints out only 1 character because you are return 'ing at the end of the 1st loop iteration.但是,更重要的是,您的代码仅打印出 1 个字符,因为您在第一次循环迭代结束时return 'ing。 Get rid of the return statement inside the loop, it doesn't belong there at all.摆脱循环内的return语句,它根本不属于那里。

Also, your cout statement inside the loop is printing out the wrong array element, because you are incrementing numofCharacters before passing the read character to cout .此外,循环内的cout语句打印出错误的数组元素,因为在将读取的字符传递给cout之前,您正在递增numofCharacters And, your loop has a potential buffer overflow, if the input file has more than 35 characters in it.并且,如果输入文件中包含超过 35 个字符,则您的循环可能存在缓冲区溢出。

Try this loop instead:试试这个循环:

while ((numofCharacters < 35) &&
       inFile.get(note1[numofCharacters]) /*inFile >> note1[numofCharacters]*/)
{
    cout << note1[numofCharacters];
    ++numofCharacters;

    /* or:
    ++numofCharacters;
    cout << note1[numofCharacters-1];
    */
}

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

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