[英]why does the first version print newline as 129 but the second works just fine?
[英]Why newline does not print?
#include <stdio.h>
#include <string.h>
char str[50];
int main() {
int hasSign = 0;
printf("Enter your email: ");
scanf("%s", str);
// email validation
if (strchr(str, '@') != NULL) {
hasSign = 1;
}
printf("%s", hasSign + "\n");
return 0;
}
當我在上面的代碼中打印hasSign
的值時,如何打印換行符?
在printf("%s", hasSign + "\\n" );
行中有一個很大的錯誤printf("%s", hasSign + "\\n" );
"\\n"
實際上是一個指向 const char (const char *)
的指針,它是兩個字符的數組: [0] = '\\n'
, [1] = '\\0'
所以當你向它添加hasSign
時,它是實際上在做指針運算。
為了通過示例清楚地說明,假設hasSign
等於 0,因此hasSign + "\\n"
計算結果為0 + "\\n"
就像&"\\n"[0]
= 指向'\\n'
指針,因此新行將在這種情況下打印。
但是當hasSign
等於 1 時, hasSign + "\\n"
計算結果為1 + "\\n"
就像&"\\n"[1]
= 指向'\\0'
指針,它是一個空字符,換句話說就是 'nothing'因此在這種情況下不會打印任何內容。
對於你的問題:
當我在上面的代碼中打印 hasSign 的值時,如何打印換行符?
你可以像printf("%d\\n", hasSign);
您不能在 C 中用+
連接字符串,也不能通過添加數字和字符串將數字轉換為字符串。 你的程序編譯是因為hasSign + "\\n"
不是語法錯誤:添加一個字符串和一個整數計算為字符串內的一個指針。 如果hasSign
為0
並且hasSign
等於1
,程序將輸出換行符。
這是一個修改版本,說明了字符串和整數參數的printf
用法:
#include <stdio.h>
#include <string.h>
int main() {
char str[50];
int hasSign = 0;
printf("Enter your email: ");
if (scanf("%49s", str) != 1) { // prevent scanf from writing beyond s[49]
// exit upon input error
return 1;
}
// email validation
if (strchr(str, '@') != NULL) {
hasSign = 1;
}
printf("email: %s, hasSign: %d\n", str, hasSign);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.