c++ - 名称格式 Lab
问题描述
C++ - 我的代码有一个大问题,我不明白我在哪里犯了错误,因为我没有得到我想要的结果,例如问题问我的第一个输出:(
#include <iostream>
#include <string>
using namespace std;
int main() {
string firstName, middleName, lastName, theName;
getline(cin, theName);
int findN = theName.find(" ");
firstName = theName.substr(0, findN);
int findN2 = theName.find(" ", findN + 1);
if (findN2 != string::npos){
middleName = theName.substr(findN2 + 1, findN2 - findN - 1);
lastName = theName.substr(findN2 + 1, theName.length() - findN2 - 1);
cout << lastName << ", " << firstName[0] << "." << middleName[0] << "." << endl;
}
else {
lastName = theName.substr(findN + 1, theName.length() - findN - 1);
cout << lastName << ", " << firstName[0] << " . " << endl;
}
return 0;
}
解决方案
我建议学习使用调试器。
#include <iostream>
#include <string>
using namespace std;
int main() {
string firstName, middleName, lastName, theName;
getline(cin, theName);
int findN = theName.find(" ");
firstName = theName.substr(0, findN);
int findN2 = theName.find(" ", findN + 1);
if (findN2 != string::npos) {
//changed from findN2 + 1 to findN + 1
middleName = theName.substr(findN + 1, findN2 - findN - 1);
lastName = theName.substr(findN2 + 1, theName.length() - findN2 - 1);
cout << lastName << ", " << firstName[0] << "." << middleName[0] << "." << endl;
}
else {
lastName = theName.substr(findN + 1, theName.length() - findN - 1);
//fixed the white space " . " -> ". "
cout << lastName << ", " << firstName[0] << ". " << endl;
}
return 0;
}
推荐阅读
- javascript - Firebase js库从非空数据库中检索空数据
- sql - 赞成票和反对票的数据库
- mysql - RMySQL - dbWriteTable() - 此 MySQL 版本不允许使用的命令
- php - PHP日期时间转换给了我错误的时间
- numpy - 用 Mathematica 和 Python 求解超越方程
- java - 堆栈如何在链接结构中工作?
- c++ - C++访问错误,指针故障
- mysql - pymysql 和 sqlalchemy: AttributeError: 'DateTime' 对象没有属性 'translate'
- mongodb - mongodb 通过 id 查找文档,然后根据 name 字段对结果进行分组
- javascript - 使用Javascript读取JSON对象内的数组内的对象