在C中的for循环随机中断。

huangapple go评论65阅读模式
英文:

For loop in C breaks randomly

问题

我一直在处理这个C循环有一段时间了。我试图通过for循环创建一个字符串数组(我不确定我是否做得正确。我希望我是)。每当我输入一个带有空格的字符串时,for循环就会中断并跳过所有迭代。例如,如果我在命令行中输入S 1,它会中断。

这是代码:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>

int main() {
    int players;
    int jerseys;
    int count = 0;
    int i;
    scanf("%d", &jerseys);

    scanf("%d", &players);

    char size[jerseys], p[players][100];

    for (jerseys; jerseys > 0; jerseys--) {
        scanf(" %c", &size[count]);
        count++;
    }
    getchar();
    count = 0;
    for (players; players > 0; players--) {
        /*scanf(" %s", p[0] );    */    /*你不能在C中分配数组。*/
        getchar();
        fgets(p[count], 100, stdin);
        printf("%s", p[count]);
        printf("%c", p[count][2]);  /* 第29行 */
        printf("Hello\n");
        count++;
    }

    return 0;
}

此外,在第29行,如果我将索引从2更改为1,循环会立即中断,无论我放入什么。

我有一个Python代码,从C中本质上想要的:

given = []
jerseys = int(input())
if jerseys == 0:
    print(0)
players = int(input())
j = []
requests = 0
for _ in range(jerseys):
    size = input()
    j.append(size)
for _ in range(players):
    p = input().split()

我已经查看了很多地方,我认为问题出在数组上,而不是换行符,但我一点头绪。

编辑:

这是看起来像我想要输入的内容(也是我通常尝试的内容):

3
3
S
M
L
S 1
S 3
L 2
英文:

I've been struggling with this loop in C for a while now. I'm trying to create a string array through a for loop (which I'm not sure I'm doing correctly. I hope I am). Every time I enter a string with a space in it, the for loop breaks and skips all iterations. For example, if I write S 1 in the command line, it would break.

This is the code:

#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;math.h&gt;
#include &lt;string.h&gt;

int main(){
	int players;
	int jerseys;
	int count = 0;
	int i;
	scanf(&quot;%d&quot;, &amp;jerseys);
	
	scanf(&quot;%d&quot;, &amp;players);
	
	char size[jerseys], p[players][100];

	for(jerseys; jerseys &gt; 0; jerseys--){
		
		scanf(&quot; %c&quot;, &amp;size[count]); 
		count++;
	}
	getchar();
	count = 0;
	for(players; players&gt;0; players--){
		/*scanf(&quot; %s&quot;, p[0] );	*/	/*you cant assign arrays in C.*/
		getchar();
		fgets(p[count], 100, stdin);
		printf(&quot;%s&quot;, p[count]);
		printf(&quot;%s&quot;, p[count][2]);  /* LINE 29 */
		printf(&quot;Hello\n&quot;);
		count ++;
	}		


	return 0;
}

Moreover, on line 29, if I change the index from 2 to 1, the loop instantly breaks, no matter what I put.

I have a python code for what I essentially want from C:

given = []
jerseys = int(input())
if jerseys == 0:
	print(0)
players = int(input())
j = []
requests = 0
for _ in range(jerseys):
	size = input()
	j.append(size)
for _ in range(players):
	 p = input().split()

I've looked at many places, and I think the problem is with the array, not the new lines, but I have no clue.

Edit:

This is something that would look like what I want to input(and what I usually try):

3
3
S
M
L
S 1
S 3
L 2

答案1

得分: 1

> 如果输入的字符与控制字符不匹配或者与格式化输入的类型不符,那么scanf将终止,留下有问题的字符作为下一个要读取的字符。

如果你在命令行中输入*1\,那么jerseys会被设置为1,但players会是一个随机整数,因为不匹配%d的格式。所以在你的程序中,players`变量可能是一个很大的整数。

所以当你使用scanf时,最好检查返回值,如下所示:

if (scanf("%d", &players) != 1) {
    /* 处理错误 */
}

我运行代码时出现了分段错误

英文:

> If the input characters do not match the control characters or are of the wrong type for a formatted input scanf terminates leaving the offending character as the next character to be read.

If you write 1` in the command line, then jerseys set to 1, but players is a random int because the ` not match the %d format. So in you program, your players variable may be a big int.

So when you use scanf, you'd better to check the return value like

if ((scanf(&quot;%d&quot;, &amp;players) != 1) {
    /* error handle */
}

I run the code and segmentation fault is raise.

答案2

得分: 1

发布的代码无法干净地编译!

以下是来自 gcc 编译器的输出:

gcc -ggdb3 -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c "untitled.c" -o "untitled.o"

untitled.c: 在函数‘main’中:
untitled.c:17:5: 警告:没有效果的语句 [-Wunused-value]
   17 |     for(jerseys; jerseys > 0; jerseys--){
      |     ^~~
      
untitled.c:24:5: 警告:没有效果的语句 [-Wunused-value]
   24 |     for(players; players>0; players--){
      |     ^~~
      
untitled.c:29:18: 警告:格式‘%s’预期的参数类型是‘char *’,但参数2的类型是‘int [-Wformat=]
   29 |         printf("%s", p[count][2]);  /* LINE 29 */
      |                 ~^   ~~~~~~~~~~~
      |                  |           |
      |                  char *      int
      |                 %d
      
untitled.c:10:9: 警告:未使用的变量‘i [-Wunused-variable]
   10 |     int i;
      |         ^

编译成功完成。

请更正代码并检查C库I/O函数返回的状态。

关于:

编译成功完成。

由于编译器输出了几个警告,这个语句仅表示编译器对你的意图进行了一些(不一定正确的)猜测。

英文:

the posted code does not cleanly compile!

Here is the output from the gcc compiler:

gcc -ggdb3 -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c &quot;untitled.c&quot; -o &quot;untitled.o&quot;

untitled.c: In function ‘main’:
untitled.c:17:5: warning: statement with no effect [-Wunused-value]
   17 |     for(jerseys; jerseys &gt; 0; jerseys--){
	  |     ^~~
	  
untitled.c:24:5: warning: statement with no effect [-Wunused-value]
   24 |     for(players; players&gt;0; players--){
	  |     ^~~
	  
untitled.c:29:18: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
   29 |         printf(&quot;%s&quot;, p[count][2]);  /* LINE 29 */
	  |                 ~^   ~~~~~~~~~~~
	  |                  |           |
	  |                  char *      int
	  |                 %d
	  
untitled.c:10:9: warning: unused variable ‘i’ [-Wunused-variable]
   10 |     int i;
	  |         ^
	  
Compilation finished successfully.

Please correct the code AND check the returned status from the C library I/O functions

Regarding:

Compilation finished successfully.

since the compiler output several warnings, This statement only means the compiler made some (not necessarily correct) guesses as to what you meant.

huangapple
  • 本文由 发表于 2023年2月8日 13:22:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75381645.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定