课程
214 字
约 1 分钟
大三下
1.1 C++基础知识过关
编译原理labs/lab01-lexical-analysis·更新于 2026-09-15
1.1 C++基础知识过关
1. 任务描述
熟悉C++的输入输出流
本关任务:从键盘输入一串由字母和数字或空格组成的符号串,以 $ 作为结尾标记。分离输入串中的字母串或数字串,并计算数字之和。
测试
输入:
11 23abc4 5a$
输出:
11
23
abc
4
5
a
sum:43
编程要求
根据提示,在右侧编辑器补充代码。
开始你的任务吧,祝你成功!
2. 我的回答
文件 level1.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include <cctype> // 引入 isdigit 和 isalpha
using namespace std;
int main(int argc, char* argv[])
{
/** Begin **/
char ch;
string current_str = "";
int sum = 0;
int state = 0; // 0:空闲,1:正在读取数字,2:正在读取字母
while (cin.get(ch)) {
if (ch == '$') {
break; // 遇到正常结尾标记,跳出循环
}
if (ch == ' ' || ch == '\n' || ch == '\t') {
// 遇到空白符,结算当前缓存的字符串
if (current_str != "") {
cout << current_str << endl;
if (state == 1) {
sum += stoi(current_str);
}
current_str = "";
}
state = 0;
}
else if (isdigit(ch)) {
// 如果当前读入的是数字
if (state == 2) {
cout << current_str << endl;
current_str = "";
}
state = 1;
current_str += ch;
}
else if (isalpha(ch)) {
// 如果当前读入的是字母
if (state == 1) {
cout << current_str << endl;
sum += stoi(current_str);
current_str = "";
}
state = 2;
current_str += ch;
}
else {
// 【新增逻辑】遇到非法符号(如 #)
if (current_str != "") {
cout << current_str << endl; // 先输出遇到非法符号前的最后一个有效串
if (state == 1) {
sum += stoi(current_str); // 如果断点前是数字,记得累加
}
current_str = "";
}
cout << "error" << endl; // 输出错误提示
break; // 立即停止读取后续内容
}
}
// 循环结束后,处理在 '$' 之前正常遗留的字符串(如果是 error 跳出的,此处 current_str 已经是 "",不会执行)
if (current_str != "") {
cout << current_str << endl;
if (state == 1) {
sum += stoi(current_str);
}
}
// 输出总和
cout << "sum:" << sum << endl;
/** End **/
return 0;
}












