作为一项家庭作业,我们被要求使用 strchr 来计算单个字母在文本字符串中出现的次数。它需要将大写或小写视为相等。有人建议我们使用某种位操作。 我设法获得了一个工作程序。
但我想让程序更具交互性,方法是允许我使用 cin 输入字符串,而不是直接将字符串键入源代码(练习要求这样做)。 是否有可能做到这一点?还是我编写这段代码的方式不可能。
#include <iostream>
#include <cstring>
using namespace std;
int main(){
const char *C = "This is a necesarry test, needed for testing.";
char target = 'A';
const char *result = C;
const char *result2;
int count = 0;
int j[26] ={0};
//================================================================================================================================================
for(int i = 0; i <= 51; i++){
if (i == 26){
target = target + 6;
}
result2 = strchr(result, target);
while(result2 != NULL){
if (result2 != NULL){
result2 = strchr(result2+1, target);
if (i <= 25){
j[i] = j[i] +1;
}
if(i > 25){
j[i-26] = j[i-26] +1;
}
cout << target << "\t";
}
}
cout << target << endl;
target++;
}
char top = 'a';
for(int o = 0; o<= 25; o++){
cout << "________________________________\n";
cout << "|\t" << top << "\t|\t" << j[o] << "\t|" << endl;
top++;
}
cout << "________________________________\n";
}
最佳答案
只需使用 getline() 从控制台获取一串字符。使用 getline,您还可以考虑用户输入中的空格。
string input;
getline(cin, input);
现在要将其与 strchr 函数一起使用,您只需将其转换为 C 类型的字符串,操作如下:
input.c_str
这将返回一个 C 类型的字符串,因此您可以将其作为函数的参数,
你需要
#include <string>
关于c++ - 如何使用 cin 获取字符串而不是对其进行硬编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41150183/