[英]Why can't I scanf and printf an integer?
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <sstream>
using namespace std;
struct person
{
int age;
string name[20], dob[20], pob[20], gender[7];
};
int main ()
{
person person[10];
cout << "Please enter your name, date of birth, place of birth, gender, and age, separated by a space.\nFor example, John 1/15/1994 Maine Male 20: ";
scanf("%s %s %s %s %d", &person[0].name, &person[0].dob, &person[0].pob, &person[0].gender, &person[0].age);
printf("%s %s %s %s %d", &person[0].name, &person[0].dob, &person[0].pob, &person[0].gender, &person[0].age);
return 0;
}
我試圖掃描並打印用戶的年齡,但它給了我2749536為person.age
值。 這是為什么?
首先,在person
的聲明中將string
更改為char
:
struct person
{
int age;
char name[20], dob[20], pob[20], gender[7];
// ^^^^
};
然后,您需要在對printf
的調用中從&person[0].age
中刪除&符,因為您要傳遞的是int
的地址,而不是其值。 還要從scanf
和printf
調用的字符串中刪除與號:
scanf("%s %s %s %s %d", person[0].name, person[0].dob, person[0].pob, person[0].gender, &person[0].age);
// Only one ampersand is needed above: -------------------------------------------------^
printf("%s %s %s %s %d", person[0].name, person[0].dob, person[0].pob, person[0].gender, person[0].age);
您應該將age
類型從float
更改為int
。
否則,將%f
用作float
類型。
另外,按照dasblinkenlight先生的建議 ,將string
更改為char
。
然后,在有printf()
情況下,從&person[0].age
中刪除&
。 您要打印變量的值,而不是地址。 FWIW,要打印地址,應使用%p
格式說明符並將參數轉換為(void *)
。
不要混淆它們並期望它們起作用。 如果為提供的格式說明符提供了不合適的參數類型,則最終將導致未定義的行為 。
故事的寓意:啟用編譯器警告。 大多數時候,他們會警告您潛在的陷阱。
您正在將值的地址傳遞給printf
。 對於傳遞給printf
所有參數和傳遞給scanf
的字符串,請刪除&
。 也正如其他人所說的,將%f
用作浮點數或將age
更改為int
。
您在這里有一個錯誤:
printf("%s %s %s %s %d", &person[0].name, &person[0].dob, &person[0].pob, &person[0].gender, &person[0].age);
它應該是:
printf("%s %s %s %s %d", person[0].name, person[0].dob, person[0].pob, person[0].gender, person[0].age);
因為,當您在printf函數中使用“&”時,您正在打印變量的地址而不是其值。 因此請記住,您只需使用'&'即可掃描任何內容,而無需打印。
年齡奇怪的原因是您輸出的是person [0] .age的地址,而不是值。 printf()取值,scanf()取地址。 您可能還希望用char *數組代替字符串對象。 下面的代碼進行編譯(盡管有一些合理的警告),並確實打印了正確的輸出(經過測試):
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <sstream>
using namespace std;
struct person
{
int age;
char name[20], dob[20], pob[20], gender[7];
};
int main ()
{
person person[10];
cout << "Please enter your name, date of birth, place of birth, gender, and age, separated by a space.\nFor example, John 1/15/1994 Maine Male 20: ";
scanf("%s %s %s %s %d", &person[0].name, &person[0].dob, &person[0].pob, &person[0].gender, &person[0].age);
printf("%s %s %s %s %d", &person[0].name, &person[0].dob, &person[0].pob, &person[0].gender, person[0].age);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.