我对C编程非常陌生。我在其他Web开发语言方面拥有广泛的背景。我在网上查找了简单的数字游戏并进行了复制和粘贴。为了检查我的理解,我也评论了一些事情。我尝试调试并意识到,当输入字符串时,整个代码都会中断。我只需要快速回答一个非常基本的问题:如何找到字符串中的字母。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*Attempting to optimize number game in C*/
// immediate bug: runs FOREVER if text is entered
int main(void) {
srand(time(NULL)); //I do not know
int r = rand() % 10 + 1; //Random number
int correct = 0; //number correct from guess
int guess; // Instance of guess
int counter = 0; // Counter; how many tries
const char* characters["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"];// this is my var/*
int c = 0, count[26] = { 0 }, x;
*/
char string = [100];
printf("Guess my number! "); // Does not need to repeat because of conditional statements below...
do { //Runs at least once... [
scanf("%d", &guess); // Takes in a number %d = int
/*
while (string[c] != '\0') {
if (string[c] >= 'a' && string[c] <= 'z') {
x = string[c] - 'a';
count[x]++
}
c++;
}
*/
if (guess ==)
if()
if (guess == r) { // Check if true
counter++; // Increment counter by 1
printf("You guessed correctly in %d tries! Congratulations!\n", counter); //
correct = 1;
}
if (guess < r) { // check if less than
counter++;
printf("Your guess is too low. Guess again. ");
}
if (guess > r) { // check if more than
counter++;
printf("Your guess is too high. Guess again. ");
}
} while (correct == 0); // If correct is null. ]
return 0;
}
答案 0 :(得分:0)
标准C库具有许多用于字符串操作的函数,例如strcpy,strncpy,strlen,strchr,strcat等。 您可以使用“ strchr”功能在字符串中找到字母。 例如:
#include <stdio.h>
#include <string.h>
int main()
{
const char *astring="Stack Owerflow";
char *ptr = strchr(astring, 'O');
printf("Found:%c on position: %d\n",*ptr, ptr-astring);
}
/ *输出: 找到:O就位:6 * /