首页 > 解决方案 > 名称格式 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;
}

标签: c++arraysstringif-statementhelper

解决方案


我建议学习使用调试器。

#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;
}

推荐阅读