C++中的字母大写

C++中的字母大写,c++,user-input,capitalization,C++,User Input,Capitalization,我有一个作业,用户以姓、名的格式输入学生姓名。你能帮我找出名字和姓氏的首字母大写的方法吗 我用它将用户输入转换成数组,这样我就可以将第一个字母大写,但当我这样做时,我很难让它在for循环之外工作 for (int x = 0; x < fName.length(); x++) { fName[x] = tolower(fName[x]); } fName[0] = toupper(fName[0]); 我使用了您的代码,并在其周围添加了一些解析。你真的很接近。如果您对代码

我有一个作业,用户以姓、名的格式输入学生姓名。你能帮我找出名字和姓氏的首字母大写的方法吗


我用它将用户输入转换成数组,这样我就可以将第一个字母大写,但当我这样做时,我很难让它在for循环之外工作

for (int x = 0; x < fName.length(); x++) 
{ 
    fName[x] = tolower(fName[x]); 
} 
fName[0] = toupper(fName[0]);

我使用了您的代码,并在其周围添加了一些解析。你真的很接近。如果您对代码有任何疑问,请告诉我

我情不自禁。对于用户输入,我总是使用getline后跟stringstream来解析行中的单词。我发现它避免了很多让我陷入流沙的边缘案例

当getline获得一个输入时,除非有问题,否则它将返回true。如果用户输入Ctrl-d,它将返回false。Ctrl-D基本上是一个EOF文件结束代码,在这种情况下,只要您不试图从调试器内部输入Ctrl-D,它就可以正常工作。我的不喜欢那样

注意,我使用std::string代替数组。string可以被视为订阅的数组,但它打印得很好,并且具有其他功能,可以更好地处理字符串

#include <iostream>
#include <string> // Allow you to use strings
#include <sstream>

int main(){

  std::string input_line;
  std::string fName;
  std::string lName;

  std::cout << "Please enter students as  <lastname>, <firstname>\n"
               "Press ctrl-D to exit\n";

  while(std::getline(std::cin, input_line)){
    std::istringstream ss(input_line);

    ss >> lName;
    // remove trailing comma.  We could leave it in and all would work, but
    // it just feels better to remove the comma and then add it back in
    // on the output.
    if(lName[lName.size() - 1] == ',')
      lName = lName.substr(0, lName.size() - 1); // Substring without the comma

    ss >> fName;

    for (int x = 0; x < fName.length(); x++)  // could start at x=1, but this works.
    {
      fName[x] = tolower(fName[x]);  // make all chars lower case
    }
    fName[0] = toupper(fName[0]);

    for (int x = 0; x < lName.length(); x++)
    {
      lName[x] = tolower(lName[x]);
    }
    lName[0] = toupper(lName[0]);

    std::cout << "Student: " << lName << ", " << fName << std::endl;
  }
}

你被卡在哪一部分?当我不知道问题出在哪里时,很难帮上忙。或者你只是想让我为你写代码?像往常一样,把问题分解,你如何循环一个字符串的后面部分?如何检测字母是否是名称的第一个字母?如何获得小写字母的大写版本?回答问题,把问题放在一起,解决问题。我用它把用户输入转换成数组,这样我就可以把第一个字母大写,但当我这样做时,我很难让它在for循环的另一端工作。对于int x=0;x