简体   繁体   中英

input string with spaces on FOR LOOP c++

I already know how to input a string with space in c++, but it doesn't work in a for loop, already tried some variants of this:

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

Can someone show me what I'm doing wrong?

edit as requested:

this is a dummie struct to show

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

The error I get while compiling:

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&))

Whatever your problem is, it is likely not with the getline() function.

Try reformatting your question.

Possible solution:

Check if you are using cin earlier in your code, as this is what will cause the bug. You should not mix input streams. If you do use cin, add a cin.ignore() after and this will fix your issue.

If you are not using cin, debug your program, as getline() within a for loop works fine.

The previous answer brought me to the fix, so all credit goes to him/her. Just to update: I was already using cin in getline(cin, obj[i]); so when I wrote cin >> gave me errors for using it twice. Rookie mistake, just removed cin >> and worked normally.

Correct use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM