3

我的程序按预期工作,直到我将上半部分添加到我的程序中。我试过查看我的错误代码,但它并没有真正帮助。错误是:

没有匹配的函数来调用预期的 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;
}
4

2 回答 2

3

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

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

然后它应该按预期工作。 现场演示在这里

正如 MM 在评论中有用地指出的那样,您还应该在访问它们的第一个字符之前检查您的字符串是否为空,即类似于

if (!firstname[i].empty()) firstname[i][0] = toupper(...);

强烈推荐。

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

于 2016-10-06T21:16:34.927 回答
2

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

 #include <ctype.h>

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

改用这个:

#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;
}
于 2016-10-06T21:03:06.123 回答