在 C 語言中使用 scanf() 語句時出現的常見錯誤是什麼?
問題
在 C 語言中,使用 scanf() 函式讀取字串和數值資料時出現的常見錯誤是什麼?
解決方案
scanf() 函式用於讀取來自 C 語言 stdin 的格式化輸入。它返回寫入其中的字元的總數,否則返回負值。
通常在使用 scanf() 函式從使用者讀取整數後讀取字串值時,我們會經常遇到錯誤。
示例
以下是一個讀取班號(整數值)和學生姓名(字串)的 C 程式 −
#include <stdio.h>
struct student {
char name[10];
int roll;
} s;
int main(){
printf("Enter information of students:
");
printf("
Enter roll number: ");
scanf("%d", &s.roll);
printf("
Enter name: ");
gets(s.name);
printf("
Displaying Information of students:
");
printf("
Roll number: %d\t", s.roll);
printf("
name:%s\t", s.name);
return 0;
}輸出
在上面的示例中,班號已由編譯器讀取,此後編譯器無法讀取姓名,並轉到 printf("Roll Number is: %d\t, s.roll);
and the output is "Roll number: 3 name: "
這是在 C 語言中使用 scanf() 函式讀取字串和數值資料時出現的常見錯誤。
Enter information of students: Enter roll number: 3 Enter name: //error Displaying Information of students: Roll number: 3 name: //error
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP