簡體   English   中英

如何在C ++中將某些字符復制到字符串中

[英]how can I copy some characters into string in c++

在代碼的一部分中,我應該一個接一個地獲得字符。 這很容易,但是我的問題是如何將這些字符一個接一個地添加到字符串中。 請注意,我不知道會得到多少個字符。 重要的是僅將字符復制為字符串。 換句話說,我想根據字符生成單詞,直到字符不等於' ''\\n'為止。 我寫的錯誤代碼是:

 char c;
 string str = NULL;
 cin.get(c);
 while (c != " ")
 {
      str += c;
      cin.get(c);
 }
 cout << str ; 

例如,如果字符c首先是'H' ,然后是'i' ,則我希望字符串coutcout上是"Hi"

=! 應該是!= ,字符串" "應該是字符' '

如果要檢查換行符和空格:

while (c != ' ' && c != '\n')

也許

while (!std::isspace(c))

它將讀取最多任何空白字符。

您還應該檢查流的結尾或其他問題:

while (cin.get(c) && !std::isspace(c)) {
    str += c;
}

如果您只想閱讀直到空格或換行符:

std::getline( cin, str, ' ' );

C ++ stringstreams建立字符串時也很有用

stringstream ss;
while (cin.get(c) && !std::isspace(c)) {
    ss << c;
}
string s = ss.str();
cout << s;

代碼中的錯誤是您沒有檢查換行符。 同樣,它應該是!=而不是=! 第二個選項在您的代碼中實際上將表現為c = (!(" ")) 另一個錯誤是您應該檢查空格字符' '而不是空字符串" "

這是正確的代碼:

char c;
string str = "";
while (true)
{
     cin.get(c);
     cout << "c is " << c << endl;       
         if ((c == ' ') || (c == '\n'))
     break;
     str += c;
}
cout << str << endl ; 

另外,如果您的要求是在遇到空格字符時停止I / O,請參考以下問題: C-在鍵入字符時從stdin讀取

此處提出的所有解決方案將繼續讀取輸入,直到輸入換行符為止,因為在此之前,尚未處理您的輸入,而是將其存儲在緩沖區中。

如果您的str開頭為空,這很簡單:

string str;

cin >> str; // cin's >> operator already reads until whitespace

cout << str;

如果您事先不知道它將有多少個字符,我將聲明一個std :: list,將元素壓入其中,然后將它們復制到字符串中。 這樣可以確保您不會在每次添加時都重新分配字符串內存:

char c;
list<char> buff;
cin.get(c);
while (c != ' ' && c != '\n')
{
    buff.push_back (c);
    cin.get(c);
}
string str (buff.size(), 0);
size_t i = 0;
while (!buff.empty())
{
    str[i] = buff.front();
    buff.pop_front();
    ++i;
}
cout << str ;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM