#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
int main(){
char string1 [50] {};
char string2 [50] {};
cout << "enter the string 1: ";
cin.get(string1,50);
cout << "your string1: " << string1 << endl;
cout << "enter the string 2: ";
cin.get(string2,50);
cout << "your string2: " << string2 << endl;
cout << strcmp(string1, string2);
return 0;
}
如何使用strcmp()wit string1(with space) 和string2(with space)?
我試過的:
輸入:
abc def
輸出:
your string1: abc def
enter the string 2: your string2:
1
我想要的結果:
輸入:
abc def
abc def
輸出:
0
uj5u.com熱心網友回復:
這是問題:
cin.get(string1,50);最多讀取 49 個字符或直到遇到 a\n但它不消耗\n.
當從第一行cin.get(string2,50);到達時是輸入緩沖區中的第一個字符,所以什么都沒有被讀取。\n
我可以想出幾種方法來解決這個問題。
- 繼續使用cin.get并在第一次讀取后添加cin.ignore()以消耗
\n. 如果一行中輸入的字符超過 49 個,ignore則會導致第 50 個字符丟失。 - 切換到使用具有相同引數的cin.getline 。不同的是,它
cin.getline確實消耗了\n. 如果在一行上輸入的字符超過 49 個,則不會丟失任何字符,它將從 50 讀取到 99 或直到\n達到 a。
錯誤處理還有一些其他小的差異,它們不會影響您撰寫的代碼,但您可以查看每個鏈接的檔案以確定哪個是最好的。
- 如果可以的話,我強烈建議您使用std::string作為變數并使用std::getline來讀取資料。這樣做的好處是您不必擔心指定顯式長度。將讀取提供的資料量并調整字串大小以適應它。這將有助于填補一行提供超過 49 個字符的漏洞。
這是一個示例cin.getline,它給出了您期望的輸出。
演示
輸出:
enter the string 1:
your string1: 'abc def'
enter the string 2:
your string2: 'abc def'
0
它與您的原始代碼略有不同,因為我在字串周圍添加了單引號和幾個換行符以使其更具可讀性并有助于驗證正在發生的事情。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/531141.html
