现在希望通过窗口输入一串数字+字母,如:
2 3 null 7 8 9
在读入之后,将null转化为 9999999,其余数字不变
最后保存到一个整型数组中。
尝试了vector和string的做法,都无法实现,求指教。
#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
using namespace std;
const int N = 110;
int nums[N];
int main()
{
string input;
getline(cin, input); // 读取一行数据
stringstream ss(input); // 将字符串转化为数据流
string temp;
int index = 0;
while (ss >> temp) // 从数据流中读取一个字符串
{
if (temp == "null") // 如果为null,转化为99999
nums[index++] = 99999;
else
nums[index++] = stoi(temp); // 将字符串转化为数字
}
// 输出结果
for (int i = 0; i < index; i++)
cout << nums[i] << " ";
return 0;
}
int main()
{
string s;
vector<int> vect;
int n;
while (1)
{
cin >> s;
if (s == "null")
n = 9999999;
else
n = stoi(s);
if (n == -1)
break;
vect.push_back(n);
}
for (auto i : vect)
cout << i << endl;
}
#include <iostream>
#include <sstream> // for stringstream
#include <string> // for string
int main()
{
std::string input_string;
std::getline(std::cin, input_string); // 读入字符串
std::stringstream input_stream(input_string); // 创建字符串流
int array[10];
int i = 0;
while (input_stream)
{
std::string token;
input_stream >> token;
if (token == "null")
{
array[i] = 9999999;
}
else
{
array[i] = std::stoi(token); // 将字符串转换为整数
}
i++;
}
return 0;
}