C++ 在C+中查找非空白字符+;
对于我的赋值,我必须调用一个函数,该函数接受用户输入并吐出非空白字符的数量。在程序内部,我有以下代码:C++ 在C+中查找非空白字符+;,c++,C++,对于我的赋值,我必须调用一个函数,该函数接受用户输入并吐出非空白字符的数量。在程序内部,我有以下代码: int GetNumOfNonWSCharacters(const string givenText) { int counter; for (int i = 0; i < givenText.length(); i++) { if (givenText.at(i) != ' ') { counter++; }
int GetNumOfNonWSCharacters(const string givenText) {
int counter;
for (int i = 0; i < givenText.length(); i++) {
if (givenText.at(i) != ' ') {
counter++;
}
}
return counter;
}
int GetNumOfNonWSCharacters(常量字符串givenText){
整数计数器;
for(int i=0;i
当我返回计数器整数时,我是这样输出的,字符串sampleText是输入:
if (menuInput == 'c' || menuInput == 'C') {
cout << "Number of whitespaces: " << GetNumOfNonWSCharacters(sampleText) << endl;
}
if(menuInput=='c'| | menuInput=='c'){
cout必须初始化计数器变量,否则它将包含任何旧值
int counter=0;
如果使用计数器
而不先初始化它,那么在程序开始使用之前,它的内存地址上会有任何垃圾内存(声明变量时,C++不会自动将内存归零)。将其复制到新文件中时,它会起作用,这完全是巧合
修复方法只是在使用计数器之前将其初始化为0:
int counter=0;
使用算法计算非空白的数量有更简单的方法:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string userString;
cout << "Enter some text" << endl;
getline(cin, userString);
cout << "You entered: " << userString << endl;
//count the number of white spaces
int numberOfWhiteSpace = count(userString.begin(), userString.end(), ' ');
//substruct that number from the total length of your string
cout << "number of non-whitespace: " << userString.length() - numberOfWhiteSpace;
return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main(){
字符串用户字符串;
cout在某些编程语言中,如果变量已分配但未分配,则称其为“垃圾值”,也就是说,计算机内存中随机存储的一些信息。因此,将计数器变量初始化为0int counter=0;
您可能收到一条编译器警告,您忽略了它。有一种简单的方法可以做到这一点:userString.length()-count(userString.begin(),userString.end(),“”)
如果允许您使用它,您可能也会对它感兴趣。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string userString;
cout << "Enter some text" << endl;
getline(cin, userString);
cout << "You entered: " << userString << endl;
//count the number of white spaces
int numberOfWhiteSpace = count(userString.begin(), userString.end(), ' ');
//substruct that number from the total length of your string
cout << "number of non-whitespace: " << userString.length() - numberOfWhiteSpace;
return 0;
}