0

I am stuck on how to use std::cin to read in an integer, followed by a space, and a String that comes after it.

Here is the store.txt file:

2 Hello how are you
6 Oh no
1 Welcome
5 We are closed

How do I read in a number at the start, followed by a space, and then read in the string after it?

For example, when I cin everything, then when I call the number 2, it will give me the string "Hello how are you".

TechGeek49
  • 476
  • 1
  • 7
  • 24
QianIsHere
  • 15
  • 2
  • 2
    Please [edit] your question to show the actual code you are having trouble with. Calling `operator>>` followed by `std::getline()` should suffice. – Remy Lebeau Nov 16 '20 at 07:59
  • your question boils down to "how to read a stirng that contains spaces?" because you can apply what you already know about `cin` to read the number. You just need to give it a try. – 463035818_is_not_an_ai Nov 16 '20 at 08:22
  • Does this answer your question? https://stackoverflow.com/questions/5838711/stdcin-input-with-spaces – 463035818_is_not_an_ai Nov 16 '20 at 08:22
  • 1
    and if you mix `cin` and `getline` you will sooner or later run into this: https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction – 463035818_is_not_an_ai Nov 16 '20 at 08:24

1 Answers1

0

You can use map for storing strings

In the map the keys will be the numbers whereas the values will be the strings

  • You can simply store them in a map by using cin function for the numbers first then followed by getline function for the string and storing them to map
  • After doing this you can access the string by numbers in O(1) time by subscripting process

code

#include <bits/stdc++.h>
using namespace std;

int main() {
    map<long long,string> m;
    long long n;
    
    while(cin>>n){
        string s;
        getline(cin,s);
        
        m[n]=s;
    }

   // Accessing strings by numbers before them :)
    
   cout<<m[1]<<"\n";
   cout<<m[2]<<"\n";
   cout<<m[6]<<"\n";
   cout<<m[5]<<"\n";
    
}


  • [Why should I not #include ?](https://stackoverflow.com/q/31816095/995714), [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721/995714) – phuclv Nov 17 '20 at 06:33