在 C 编程中将一个字符串变量复制到另一个字符串变量时出现问题

Getting problem copying one string variable to another string variable in c programming

#include<stdio.h>

void main()
{
    char Word1[10], Word2[10];
    int i;
    
    printf("Enter Text : ");
    scanf("%s", Word1);
    
    for (i = 0; i != '[=10=]'; i++)
    {
        Word2[i] = Word1[i];
    }
    
    Word2[i] = '[=10=]';
    printf("The text is : %s\n", Word2);
}

所以我在这里尝试将 'Word1' 复制到 'Word2' 变量但是当我打印它时

Enter Text : Harsh
The text is :

这是显示的(我希望第二行显示什么是 'Enter Text : ')

在这个for循环中

for (i = 0; i != '[=10=]'; i++)

变量i初始化为0

i = 0;

所以这个条件

i != '[=12=]';

立即评估为逻辑错误。

你的意思好像是

 for (i = 0; word1[i] != '[=13=]'; i++)

您可以替换此代码段

int i;
//...
for (i = 0; word1[i] != '[=14=]'; i++)
{
    Word2[i] = Word1[i];
}

Word2[i] = '[=14=]';

这个

for ( size_t i = 0; ( word2[i] = word1[i] ) != '[=15=]'; i++ );

size_t i = 0;
while ( ( word2[i] = word1[i] ) ) i++;

这是一个演示程序。

#include <stdio.h>

int main(void) 
{
    char word1[] = "Hello World!";
    char word2[sizeof( word1 )];
    
    size_t i = 0;
    while ( ( word2[i] = word1[i] ) ) i++;  
    
    puts( word2 );
    
    return 0;
}

程序输出为

Hello World!

注意根据C标准,不带参数的函数main应该声明为

int main( void )

“for”循环中的条件应为 Word1[i] != '\0'