燃烧到一个char阵列,一次一个char,没有琴弦

发布于 2025-01-31 14:41:41 字数 218 浏览 1 评论 0原文

我正在尝试从文件中获取输入,但是我需要一次进行一个字符阵列。没有数字或符号,但它只打印出第一个字母。

enter image description here
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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌辣 2025-02-07 14:41:41

您使用infile.eof()是错误的。将读取操作转移到循环条件中。并且,请考虑使用infile.get(...)而不是infile>> ...在这种情况下。

但是,更重要的是,您的代码仅打印出1个字符,因为您是返回'在第一个循环迭代结束时。摆脱返回语句在循环中,它根本不属于那里。

另外,您的cout在循环内部的语句正在打印错误的数组元素,因为您正在将读取字符传递给cout 。而且,如果输入文件中有35个字符,则您的循环具有潜在的缓冲区溢出。

改用此循环:

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

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

Your use of inFile.eof() is wrong. Move the read operation into the loop condition instead. And, consider using inFile.get(...) instead of inFile >> ... in this situation.

But, more importantly, your code prints out only 1 character because you are return'ing at the end of the 1st loop iteration. Get rid of the return statement inside the loop, it doesn't belong there at all.

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. And, your loop has a potential buffer overflow, if the input file has more than 35 characters in it.

Try this loop instead:

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

    /* or:
    ++numofCharacters;
    cout << note1[numofCharacters-1];
    */
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文