이것은 내 문제입니다. txt에서 일부 줄을 읽었습니다. 이 txt는 다음과 같습니다.문자열도 ifstream에서 가져옵니다. " n"
Ciao: 2000
Kulo: 5000
Aereo: 7000
ecc. 나는 모든 단어를 문자열 (':') 앞에 할당하고 그 다음에 맵에 할당해야한다. 숫자를 int로 매핑 한 다음지도로 전달합니다. 문제는 두 번째 줄부터 시작하여 내 문자열이 ("\ n Kulo") ecc가됩니다. 나는 이것을 원하지 않는다! 내가 무엇을 할 수 있을지? 내가 상상할 수 있지만, 당신은 또한 key.substr(0, key.length() - 1)
을 사용할 수 있습니다, 대신 임시 문자열에서-반복자의 (
for (std::string line; std::getline(file, line);)
{
std::string key;
int n;
std::istringstream iss(line);
if (!(iss >> key >> n) || key.back() != ':') { /* format error */ }
m.insert(std::make_pair(std::string(key.cbegin(), std::prev(key.cend()),
n));
}
:
#include <iostream>
#include <fstream>
#include <string>
#include <map>
using namespace std;
int main()
{
map <string, int> record;
string nome, input;
int valore;
ifstream file("punteggi.txt");
while (file.good()) {
getline(file, nome, ':');
// nome.erase(0,2); //Elimina lo spazio iniziale
file >> valore;
record[nome] = valore;
cout << nome;
}
file.close();
cout << "\nNome: ";
cin >> input;
cout << input << ": " << record[input] << "\n";
cout << "\n\n";
return 0;
}
관련 없음,하지만''\ n "'대신'std :: endl'을 사용하십시오. –
'std :: string :: substr'을 사용하여 첫 번째 문자를 건너 뛸 수 있습니다. –
@ J.N. -'std :: endl'과'\ n' -'std :: endl'을 사용하면 버퍼가 플러시됩니다. – birryree