gpt4 book ai didi

c - 为什么这段代码没有输出预期的输出?

转载 作者:行者123 更新时间:2023-12-04 20:00:37 24 4
gpt4 key购买 nike

这可能是查找错误的好问题。不?至少对于初学者来说是好的。

#define SIZE 4
int main(void){
int chars_read = 1;
char buffer[SIZE + 1] = {0};
setvbuf(stdin, (char *)NULL, _IOFBF, sizeof(buffer)-1);
while(chars_read){
chars_read = fread(buffer, sizeof('1'), SIZE, stdin);
printf("%d, %s\n", chars_read, buffer);
}
return 0;
}<code></code>
<code>

<p>Using the above code, I am trying to read from a file using redirection <code>./a.out < data</code>. Contents of input file:</p>

<pre><code>1line
2line
3line
4line
</code></pre>

<p>But I am not getting the expected output, rather some graphical characters are mixed in.
What is wrong?</p>

<hr/>

<p>Hint: (Courtesy Alok)</p>

</code><ul><code>
<li><code>sizeof('1') == sizeof(int)</code></li>
</code><li><code>sizeof("1") == sizeof(char)*2</code></li>
</ul>

<p>So, use 1 instead :-)</p>

Take a look at <a href="https://stackoverflow.com/questions/2371292/buffered-reading-from-stdin-using-fread-in-c/2378520#2378520" rel="noreferrer noopener nofollow">this post</a> for buffered IO example using fread .

最佳答案

'1' 的类型在 C 中是 int,而不是 char,所以你读的是 SIZE*sizeof(int ) 每个 fread 中的字节。如果 sizeof(int) 大于 1(在大多数现代计算机上都是这样),那么您正在读取 buffer 的存储空间。这是 C 和 C++ 不同的地方之一:在 C 中,字符字面量是 int 类型,在 C++ 中,它们是 char 类型。

因此,您需要 chars_read = fread(buffer, 1, SIZE, stdin); 因为 sizeof(char) 根据定义为 1。

事实上,我会把你的循环写成:

while ((chars_read = fread(buffer, 1, sizeof buffer - 1)) > 0) {
buffer[chars_read] = 0; /* In case chars_read != sizeof buffer - 1.
You may want to do other things in this case,
such as check for errors using ferror. */
printf("%d, %s\n", chars_read, buffer);
}

要回答你的另一个问题,'\0'int 0,所以 {'\0'} {0} 是等价的。

对于 setvbuf,我的文档说:

The size argument may be given as zero to obtain deferred optimal-size buffer allocation as usual.

为什么要用 \\ 而不是 ///* */ 来评论? :-)

编辑:根据您对问题的编辑,sizeof("1") 是错误的,sizeof(char) 是正确的。

sizeof("1") 为 2,因为 "1" 是一个包含两个元素的 char 数组:'1 '0

关于c - 为什么这段代码没有输出预期的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2378264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com