簡體   English   中英

FOR LOOP c++ 上帶有空格的輸入字符串

[英]input string with spaces on FOR LOOP c++

我已經知道如何在 c++ 中輸入帶空格的字符串,但它在 for 循環中不起作用,已經嘗試了一些變體:

for (int i; i = 0; i < 10; i++){
   cout << "Name: ";
   cin >> getline(cin, obj[i].name);
}

有人可以告訴我我做錯了什么嗎?

按要求編輯:

這是一個要顯示的虛擬結構

struct employee{
   string name;
}obj[10];

我在編譯時遇到的錯誤:

novo_teste.cpp: In function ‘int main()’:
novo_teste.cpp:49:15: error: no match for ‘operator>>’ (operand types are ‘std::istream’ {aka ‘std::basic_istream<char>’} and ‘std::basic_istream<char>’)
   49 |           cin >> getline(cin, obj[i].nome);
      |           ~~~ ^~ ~~~~~~~~~~~~~~~~~~~~~~~~~
      |           |             |
      |           |             basic_istream<[...]>
      |           basic_istream<[...]>
novo_teste.cpp:49:15: note: candidate: ‘operator>>(int, int)’ <built-in>
   49 |           cin >> getline(cin, obj[i].nome);
      |           ~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~
novo_teste.cpp:49:15: note:   no known conversion for argument 2 from ‘std::basic_istream<char>’ to ‘int’
In file included from /usr/include/c++/9/iostream:40,
                 from novo_teste.cpp:1:
/usr/include/c++/9/istream:120:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__istream_type& (*)(std::basic_istream<_CharT, _Traits>::__istream_type&)) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>]’
  120 |       operator>>(__istream_type& (*__pf)(__istream_type&))

無論您的問題是什么,都可能getline() function 無關。

嘗試重新格式化您的問題。

可能的解決方案:

檢查您是否在代碼的前面使用了 cin,因為這會導致錯誤。 您不應該混合輸入流。 如果您確實使用了 cin,請在之后添加一個 cin.ignore() ,這將解決您的問題。

如果您不使用 cin,請調試您的程序,因為 for 循環中的 getline() 可以正常工作。

先前的答案使我得到了解決,因此所有功勞都歸於他/她。 只是為了更新:我已經在getline(cin, obj[i]);中使用了 cin 所以當我寫cin >>給了我兩次使用它的錯誤。 菜鳥的錯誤,剛剛去掉了cin >>就可以正常工作了。

正確使用:

for (int i; i = 0; i < 10; i++){
   cout << "Name: ";
   getline(cin, obj[i].name);
}

暫無
暫無

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

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