如何在 C++ 中输入一个整数后跟一个字符串?
How to input an integer followed by a String in C++?
我无法理解如何使用 std::cin
读取整数,然后是 space,然后是字符串。
这是 store.txt
文件:
2 Hello how are you
6 Oh no
1 Welcome
5 We are closed
如何在开头读入数字,然后读入 space,然后读入后面的字符串?
例如,当我cin
一切,那么当我拨打号码2时,它会给我字符串"Hello how are you"
。
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";
}
我无法理解如何使用 std::cin
读取整数,然后是 space,然后是字符串。
这是 store.txt
文件:
2 Hello how are you
6 Oh no
1 Welcome
5 We are closed
如何在开头读入数字,然后读入 space,然后读入后面的字符串?
例如,当我cin
一切,那么当我拨打号码2时,它会给我字符串"Hello how are you"
。
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";
}