簡體   English   中英

如何修復我的 C++ 程序? 該程序應該使用 function 獲取字符串中的空格數

[英]How can I fix my C++ program? The program is supposed to get the number of spaces in a string with a function

代碼:

#include <iostream>
#include <string>
using namespace std;

/**
   Gets the number of spaces in a string.
   @param str any string
   @return the number of spaces in str
*/

string count_spaces(string hi) {
   int spaces;
   for (int i = 0; i < hi.length(); i++) {
      if (hi.substr(i, 1) == " ")
          spaces +=1;
   }
   return spaces;
}

int main()
{
   string str;
   getline(cin, str);
   cout << count_spaces(str) << endl;
   return 0;
}

我不確定為什么我的 C++ 程序會出現此錯誤。 spaces在程序中是一個int值。

Error: helper_function.cpp: In function ‘std::string count_spaces(std::string)’:
helper_function.cpp:17:8: error: could not convert ‘spaces’ from ‘int’ to ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’}
   17 | return spaces;
      |        ^~~~~~
      |        |
      |        int

我不確定如何解決它 go。

你需要

int count_spaces(string hi) 

代替

string count_spaces(string hi) 

您的count_spaces() function 被聲明為返回一個string而不是一個int 你需要解決這個問題:

int count_spaces(string hi)

此外,您需要初始化spaces ,否則當hi為空時代碼具有未定義的行為,因為它將返回一個不確定的值:

int spaces = 0;

此外, if (hi.substr(i, 1) == " ")可以簡化為if (hi[i] == ' ')spaces +=1; 簡化為++spaces; .

雖然,您應該考慮使用標准的std::count()算法而不是手動計算字符數:

#include <algorithm>

...

size_t count_spaces(string hi) {
   return count(hi.begin(), hi.end(), ' ');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM