[英]Basic c program doesn't continue after the final scanf in the function, scanf just keeps accepting input endlessly
[英]Scanf function not accepting input
我正在使用名為'student'的結構編寫一個簡單的C程序。 這是我的代碼
#include<stdio.h>
#include<stdlib.h>
struct student {
char name[50];
int id;
float marks_1;
float marks_2;
};
void main(){
int num,a,i;
printf("Enter number of students\n");
scanf("%d",&num);
struct student s[num];
for(i=0;i<num;i++)
{
a=i+1;
printf("Enter name of student number %d\n",a);
scanf("%[^\n]%*c",s[i].name);
}
}
當我運行該程序時,我能夠正確輸入學生人數,但之后我無法輸入與每個學生相對應的名稱。 這是我得到的輸出。
Enter number of students
2
Enter name of student number 1
Enter name of student number 2
RUN FINISHED; exit value 2; real time: 1s; user: 0ms; system: 0ms
可能是什么問題? 任何幫助贊賞
scanf("%d",&num);
離開您鍵入的換行符,將輸入發送到輸入緩沖區中的程序。 因此,第一次迭代
for(i=0;i<num;i++)
{
a=i+1;
printf("Enter name of student number %d\n",a);
scanf("%[^\n]%*c",s[i].name);
}
立即找到該換行符並掃描一個空字符串。
掃描前可以使用換行符,方法是將第一種格式更改為"%d%*c"
或者在名稱掃描格式的開頭添加一個空格以跳過初始空白。
更改scanf("%[^\\n]%*c",s[i].name);
to scanf(" %[^\\n]%*c",s[i].name);
。 注意在說明符之前給出的空間消耗stdin中剩下的最后一個輸入字符。
Scanf函數不接受輸入
如果scanf()
不起作用,請使用fgets()
:
fgets(s[i].name, sizeof(s[i].name), stdin);
如果/雖然您對它的工作方式沒有一個完整,正確的了解,請遠離scanf()
,因為這樣使用起來不直觀。 (如果您不夠小心,也是不安全的,在這種情況下,您不是很安全。該代碼易於發生緩沖區溢出。)
我不確定你在這里要做什么:
scanf("%[^\n]%*c",s[i].name);
但嘗試將其替換為:
scanf("%50[^\n]s",s[i].name);
要讀取c中包含空格的行,請使用fgets (name, 100, stdin);
這是完整的代碼:
#include<stdio.h>
#include<stdlib.h>
struct student {
char name[50];
int id;
float marks_1;
float marks_2;
};
void main(){
int num,a,i;
printf("Enter number of students\n");
scanf("%d",&num);
struct student s[num];
for(i=0;i<num;i++)
{
a=i+1;
printf("Enter name of student number %d\n",a);
fgets (s[i].name, 50, stdin);
}
}
scanf
將讀取直到第一個空格,但不是fgets
,但是,如果你在使用fgets
時按Enter鍵,它也將被存儲在字符串中。 因此您需要在以后將其刪除
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.