![](/img/trans.png)
[英]how to ignore/skip white spaces when reading from a textfile using string getline in c++
[英]Ignore Spaces Using getline in C++ Palindrome homework
我試圖使用getline();
跳過代碼中的空格getline();
我想我解決了間距問題,但是我試圖同時從單詞的開頭和單詞的結尾進行代碼檢查,以便當我輸入“ ufo tofu”之類的句子時,它會回來作為回文。
我試過刪除空格,但這只會導致系統返回錯誤。
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string userInput;
int startInput;
int endInput;
bool isPalindrome = true;
startInput = userInput.length();
getline (cin, userInput);
cin.ignore();
for (int i = 0; i<(startInput/2); i++){
if (userInput[i] != userInput[(startInput -1) -i])
isPalindrome = false;
}
if (isPalindrome){
cout << userInput << " is a palindrome" << endl;
}
else {
cout << userInput << " is not a palindrome" << endl;
}
return 0;
}
當我提交要評分的代碼時,我試圖使輸出返回為“不是回文”。
這是又回來的兩個錯誤。
4: Compare output 0 / 2 Output differs. See highlights below. Special character legend Input statistics Your output statistics is a palindrome Expected output statistics is not a palindrome 6: Compare output 0 / 2 Output differs. See highlights below. Special character legend Input evil is alive Your output evil is alive is a palindrome Expected output evil is alive is not a palindrome
string s;
do {
getline(cin, s);
}while(s.empty());
s.erase((remove(s.begin(),s.end(),' ')),s.end());
cout<<s<<endl;
假設您的字符串s
是ufo tofu
。 刪除所有空間后,它將變為ufotofu
。 這樣,您可以輕松地檢查回文是否正確。
這東西是怎么工作的?
s
的字符串。 在該字符串中,我們將存儲我們的ufo tofu
輸入。 getline(cin, s);
,但是如果您按Enter鍵一次,它將停止您的程序。 remove
和erase
函數的函數組合:作為開始參數,我們使用function remove
,它查找字符串中的所有空格,將它們推到容器的末尾(在我們的示例中為string s
),然后返回開頭第二個參數告訴我們從開始的迭代器到末尾刪除容器的每個元素。 我認為這是一種非常簡單的方法,但是如果對您沒有用,很抱歉浪費您的時間閱讀所有這些內容! :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.