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
  • 336
  • 1
  • 3
  • 16
QianIsHere
  • 13
  • 2

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