【发布时间】:2015-10-02 07:28:44
【问题描述】:
我主要用 Java 开发软件,但目前我正在尝试用 C 语言做一些事情,但遇到了一个奇怪的问题。
我使用scanf() 方法更改字符串的值,但scanf() 不仅更改参数化字符串的值,它还更改其他字符串的值。
现在我的问题是:我只是被开发人员友好的 Java 宠坏了,而且我太笨了,无法正确使用它吗?我看不出我在哪里做错了。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char lFileType[] = ".txt";
char lFilePath[] = "C:\\Notenverwaltungssystem";
char lFileFinalPath[] = "";
char lFileName[] = "";
printf( "lFileType before scanf: " );
printf( "%s \n", lFileType );
printf( "lFilePath before scanf: " );
printf( "%s \n", lFilePath );
printf( "lFileName before scanf: " );
printf( "%s \n", lFileName );
printf( "lFileFinalPath before scanf: " );
printf( "%s \n\n", lFileFinalPath );
printf( "Bitte geben Sie den Namen der Pruefung an: \n\n" );
scanf( "%s", &lFileName );
printf( "\nlFileType after scanf: " );
printf( "%s \n", lFileType );
printf( "lFilePath after scanf: " );
printf( "%s \n", lFilePath );
printf( "lFileName after scanf: " );
printf( "%s \n", lFileName );
printf( "lFileFinalPath after scanf: " );
printf( "%s \n\n", lFileFinalPath );
system("PAUSE");
return 0;
}
预期输出:
lFileType before scanf: .txt
lFilePath before scanf: C:\Notenverwaltungssystem
lFileName before scanf:
lFileFinalPath before scanf:
Bitte geben Sie den Namen der Pruefung an:
Test
lFileType after scanf: .txt
lFilePath after scanf: C:\Notenverwaltungssystem
lFileName after scanf: Test
lFileFinalPath after scanf:
Press any key to continue . . .
执行程序时得到的输出:
lFileType before scanf: .txt
lFilePath before scanf: C:\Notenverwaltungssystem
lFileName before scanf:
lFileFinalPath before scanf:
Bitte geben Sie den Namen der Pruefung an:
Test
lFileType after scanf: .txt
lFilePath after scanf: st
lFileName after scanf: Test
lFileFinalPath after scanf: est
Press any key to continue . . .
【问题讨论】:
-
关于缓冲区大小有几个答案。我想补充一点,
scanf( "%s", &lFileName )可以改为scanf( "%s", lFileName ),因为lFileName是缓冲区的地址,不需要&。