我正在尝试循环一个字符串并将其放在C ++中的地图中但由于某种原因,它会一直排除myMap[0]
并且我无法输出字符串的第一个字母。请帮忙。
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <map>
using namespace std;
int main(int argc, char *argv[])
{
int inputNumbers;
map<int,string>myMap;
cout<<"Enter how many words"<<endl;
cin>>inputNumbers;
//insert the words to the map
for(int i = 0; i < inputNumbers; i++) {
string inputNames ="";
cout<<"Enter the word #"<<i+1<<" out of "<<inputNumbers<<endl;
getline(cin, inputNames);
myMap[i] = inputNames;
cin.clear();
cin.ignore();
}
//output map
for(map<int,string>::iterator it = myMap.begin(); it != myMap.end(); it++)
cout << it->first << ":" << it->second << endl;
it->first << ":" << it->second << endl;
return 0;
}
这是输出
Enter how many words
4
Enter the word #1 out of 4
Kobe
Enter the word #2 out of 4
is
Enter the word #3 out of 4
the greatest
Enter the word #4 out of 4
ever!!!
0:
1:obe
2:s
3:he greatest
Program ended with exit code: 0
如果它是一个字符串单词(没有空格),真正的单词(只有字母),好词(字母和数字),capword(以大写字母开头),还会感谢扫描用户输入字符串并输出的额外提示,首字母缩写词(全部大写字符串)。
答案 0 :(得分:-1)
我找到了答案!!!!
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;
string inputNames;
int main()
{
string line;
vector<string> myVector;
ifstream myTextFile("myText.txt");
//stores the lines in file to myVector and pushes it back
while (getline(myTextFile, line)) {
//cout<<line<<endl;
myVector.push_back(line);
}
//outputs what's inside the vector
for(int i=0; i<myVector.size(); i++) {
cout << i << ":" << myVector[i] << endl;
}
return 0;
}