昨天华为的笔试第一题,每一行的输入包含多种数据类型,都是用逗号隔开的,因为平时习惯了用空格分隔,吃了个措手不及的亏。
空格分隔时读取输入
如果输入包含字符串、整数、小数等,用空格隔开,需要相应地修改读取输入的方式。
C++示例:
#include <iostream>
#include <string>
using namespace std;
int main() {
// 读取输入值
string str;
int a;
double b;
cin >> str >> a >> b;
// 处理数据
double sum = a + b;
// 输出结果
cout << "String: " << str << endl;
cout << "Integer: " << a << endl;
cout << "Double: " << b << endl;
cout << "Sum: " << sum << endl;
return 0;
}
Python示例:
# 读取输入值
str_value, int_value, float_value = input().split()
# 转换类型
int_value = int(int_value)
float_value = float(float_value)
# 处理数据
sum_value = int_value + float_value
# 输出结果
print("String:", str_value)
print("Integer:", int_value)
print("Float:", float_value)
print("Sum:", sum_value)
Java示例:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 读取输入值
String strValue = scanner.next();
int intValue = scanner.nextInt();
double floatValue = scanner.nextDouble();
// 处理数据
double sumValue = intValue + floatValue;
// 输出结果
System.out.println("String: " + strValue);
System.out.println("Integer: " + intValue);
System.out.println("Float: " + floatValue);
System.out.println("Sum: " + sumValue);
scanner.close();
}
}
逗号分隔时读取输入
如果输入是逗号隔开的,我们可以使用逗号作为分隔符来读取输入。
C++示例:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main() {
// 读取输入行
string input;
getline(cin, input);
// 使用 stringstream 分割输入
stringstream ss(input);
vector<string> tokens;
string token;
while (getline(ss, token, ',')) {
tokens.push_back(token);
}
// 提取数据
string str = tokens[0];
int a = stoi(tokens[1]);
double b = stod(tokens[2]);
// 处理数据
double sum = a + b;
// 输出结果
cout << "String: " << str << endl;
cout << "Integer: " << a << endl;
cout << "Double: " << b << endl;
cout << "Sum: " << sum << endl;
return 0;
}
Python示例:
# 读取输入行
input_line = input()
# 使用逗号分割输入
tokens = input_line.split(',')
# 提取数据
str_value = tokens[0]
int_value = int(tokens[1])
float_value = float(tokens[2])
# 处理数据
sum_value = int_value + float_value
# 输出结果
print("String:", str_value)
print("Integer:", int_value)
print("Float:", float_value)
print("Sum:", sum_value)
Java示例:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 读取输入行
String input = scanner.nextLine();
String[] tokens = input.split(",");
// 提取数据
String strValue = tokens[0];
int intValue = Integer.parseInt(tokens[1].trim());
double floatValue = Double.parseDouble(tokens[2].trim());
// 处理数据
double sumValue = intValue + floatValue;
// 输出结果
System.out.println("String: " + strValue);
System.out.println("Integer: " + intValue);
System.out.println("Float: " + floatValue);
System.out.println("Sum: " + sumValue);
scanner.close();
}
}
测试输入abc,520,3.14,所有程序输出均为
String: abc
Integer: 520
Float: 3.14
Sum: 523.14