[英]How can I split string and integer when user input both the string and the integer in the same line in C++?
只需從使用空格作為分隔符的std::cin
流式傳輸它們:
int n;
std::cin >> n;
for (int i = 0; i < n; ++i) {
std::string s;
int a;
std::cin >> s >> a;
// process a and s
}
嘗試這樣的事情:
#include <iostream>
#include <vector>
#include <utility>
#include <string>
#include <sstream>
#include <algorithm>
int main()
{
std::vector<std::pair<std::string, int>> phoneBook;
int n;
std::string line;
std::getline(std::cin, line);
std::istringstream(line) >> n;
for (int i = 0; i < n; ++i)
{
std::getline(std::cin, line);
std::string name;
int phoneNumber;
std::istringstream(line) >> name >> phoneNumber;
phoneBook.push_back(std::make_pair(name, phoneNumber));
}
while (std::getline(std::cin, line))
{
auto iter = std::find_if(phoneBook.begin(), phoneBook.end(),
[&](const std::pair<std::string, int> &entry){
return (entry.first == line);
}
);
if (iter != phoneBook.end())
std::cout << iter->first << "=" << iter->second << std::endl;
else
std::cout << "Not found" << std::endl;
}
return 0;
}
另一方面,如果電話簿中從來沒有任何重復的名字,請考慮使用std::map
而不是std::vector
:
嘗試這樣的事情:
#include <iostream>
#include <map>
#include <string>
#include <sstream>
int main()
{
std::map<std::string, int> phoneBook;
int n;
std::string line;
std::getline(std::cin, line);
std::istringstream(line) >> n;
for (int i = 0; i < n; ++i)
{
std::getline(std::cin, line);
std::string name;
int phoneNumber;
std::istringstream(line) >> name >> phoneNumber;
phoneBook[name] = phoneNumber;
}
while (std::getline(std::cin, line))
{
auto iter = phoneBook.find(line);
if (iter != phoneBook.end())
std::cout << iter->first << "=" << iter->second << std::endl;
else
std::cout << "Not found" << std::endl;
}
return 0;
}
您還可以使用標准函數scanf()
從C
stdin
獲取輸入,因為電話簿條目、姓名和號碼的輸入是空格分隔的。
所以,使用如下:
char name[<size>];
int num;
scanf("%s %d", &name, &num);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.