我已经在我想要输入文本的地方编写了这段代码,例如 "helloWorld"
然后比较它,如果它与输入的文本匹配,那么它应该打印该文本 101 次。但是,它不起作用,因为它似乎没有比较 if (string == "helloWorld")
中的字符串。直接跳到else
部分。请提供有关如何操作的必要详细信息。
这是我的代码:
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
char string[30];
clrscr();
printf("Enter the string 'helloWorld' if you wanna see magic\n");
scanf ("%s", string);
printf("Your enterred Input is %s\n", string);
if (string == "helloWorld")
{
for (i=0;i<=100;i++)
{
printf("%s\n",string);
}
}
else
{
printf("Invalid Input\n");
}
getch();
}
此外,我知道在 C 中如果我们使用 char variable[sting_length]
输入字符串在 C 语言中,我们必须输入不带任何空格的字符串。但是,有没有办法输入像“Hello World”这样的字符串,并且仍然打印/比较整个内容?
最佳答案
为了读取带有空格的字符串,您可以创建一个循环来读取字符,直到到达新行。
int i = 0;
char inputChar = ' ';
char* string = new char[STRING_SIZE];
do
{
getch(inputChar);
string[i] = inputChar;
i++;
} while (inputChar != '\n' && i < STRING_SIZE);
在此代码中,STRING_SIZE 是您选择的数组大小。
为了比较字符串,您必须检查每个元素以验证它们是否相同。
char compare[] = "Hello, world!";
int i = 0;
bool areEqual = true;
while (areEqual && compare[i] != '\n')
{
if(compare[i] != string[i])
{
areEqual = false;
}
}
使用这两部分代码,您应该能够读取带有空格的字符串,然后将其与您选择的任何字符串进行比较。字符串也可能有不同的长度。
关于比较 C 上的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37494433/