使用鞋帮不正确?直到我输入密码

Using to upper incorrectly? Working code until I entered toupper

本文关键字:输入 密码 不正确      更新时间:2023-10-16

我的程序像它应该工作,直到我添加了顶部部分到我的程序。我试着看我的错误代码,但它并没有真正的帮助。错误如下:

没有可调用的匹配函数需要2个参数,提供一个

所以我知道错误在while循环中的这两个语句中。我做错了什么?

我想命名为

约翰。布朗去约翰。布朗

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
int main(){
  string firstname[5];
  string lastname[5];
  ifstream fin( "data_names.txt" );
  if (!fin) {
    cout << "There is no file" << endl;
  }
  int i = 0;
  while( i < 5 && (fin >> firstname[i]) && (fin >> lastname[i]) ) {
    firstname[0] = toupper(firstname[0]);
    lastname[0] = toupper(lastname[0]);
    i++;
  }
  cout << firstname[0] << " " << lastname [0] << endl;
  cout << firstname[1] << " " << lastname [1] << endl;
  cout << firstname[2] << " " << lastname [2] << endl;
  cout << firstname[3] << " " << lastname [3] << endl;
  cout << firstname[4] << " " << lastname [4] << endl;
  return 0;
}

std::toupper适用于单个字符,但您试图将其应用于字符串。除了添加#include <cctype>,您还需要修改while循环的主体:

firstname[i][0] = toupper(firstname[i][0]);
lastname[i][0] = toupper(lastname[i][0]);
i++;

那么它应该像预期的那样工作。现场演示在这里

正如M.M在评论中指出的那样,在访问字符串的第一个字符之前,您还应该检查字符串是否为空,例如

if (!firstname[i].empty()) firstname[i][0] = toupper(...);
强烈建议使用

请注意,如果您得到像McDonald这样的名称,您可能需要更复杂的逻辑:)

您需要ctype.h来获得toupper()的正确定义。它通常不是作为函数实现的,而是作为数组映射实现的。

 #include <ctype.h>

程序有几个缺陷:使用字符串数组而不是字符串,没有正确地遍历字符串,没有声明而是使用C定义的toupper(),当文件不存在时不退出。

用这个代替:

#include <ctype.h>
#include <iostream>
#include <string>
using namespace std;
int main ()
{
  ifstream fin ("data_names.txt");
  if (!fin) 
  {
    cerr << "File missing" << endl;
    return 1;
  }
  // not sure if you were trying to process 5 lines or five words per line
  // but this will process the entire file
  while (!fin.eof())
  {
       string s;
       fin >> s;
       for (i = 0;  i < s.length();  ++i)
            s [i] = toupper (s [i]);
       cout << s << endl;
  }
  return 0;
}