Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果用户未在C中插入一个默认变量,则指定一个默认变量_C_Variables_If Statement_Scanf_Strcpy - Fatal编程技术网

如果用户未在C中插入一个默认变量,则指定一个默认变量

如果用户未在C中插入一个默认变量,则指定一个默认变量,c,variables,if-statement,scanf,strcpy,C,Variables,If Statement,Scanf,Strcpy,所以我正在做一个课堂作业,我有基本的程序,但我试图超越作业。我已从预定义的.dat文件加载,但我想让用户也可以选择定义自己的.dat文件,因此我的代码如下: #include <stdio.h> #include <stdlib.h> int main() { //Loads Variables FILE *inputFile; char *firstName[15]; char *lastName[15]; char choic

所以我正在做一个课堂作业,我有基本的程序,但我试图超越作业。我已从预定义的.dat文件加载,但我想让用户也可以选择定义自己的.dat文件,因此我的代码如下:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    //Loads Variables
    FILE *inputFile;
    char *firstName[15];
    char *lastName[15];
    char choice[15];
    printf("Welcome Friend File Importer\n");
    printf("What is the name of the file you want imported:\n");
    scanf("%s",&choice);
    printf("you entered %c\n",choice);
    if (choice == NULL)
    {   
        printf("Friends.dat Loaded By Default\n");
        choice = "friends.dat";
    }
    inputFile = fopen(choice, "r");  //Loads Input File
    //If there is an issue then let the user know
    if (inputFile == NULL)
    {
        printf("You got some issues... check to make sure the file exists.\n\n");
        system("pause");
        return -1;
    }
    //Starts to print out the friends list
    printf("\nYour friends\n\n");
    fscanf(inputFile, "%s%s", firstName, lastName);
    while (!feof(inputFile))
    {
        printf("%s %s\n", firstName, lastName);
        fscanf(inputFile, "%s%s", firstName, lastName);
    }
    fclose(inputFile);
    system("pause");
    return 0;
}
所以我想知道问题是因为我使用scanf还是因为我试图在if语句中分配一个变量。请像我五岁时那样对我说话,我有诵读困难,通过阅读学习更好。

你不能分配到数组,你必须复制到数组中。在您的情况下,应该使用。

当您要将字符串复制到另一个字符串时,必须使用strcpy

即:

choice = "friends.dat";
必须换成

strcpy(choice ,"friends.dat");
要打印字符串,应使用%s格式说明符:

printf("you entered %s\n",choice);
而不是

printf("you entered %c\n",choice);
选择是一个数组。您不能分配给数组

数组永远不会比较为NULL,因为表达式中的数组名称将衰减为其第一个元素的地址


为了检测是否没有提供合适的输入以供选择,首先使用fgets读取整行,然后使用sscanf解析该行更容易。scanf和sscanf都返回保存的参数数。因此,如果scanf%s,choice返回1,则表示它成功地在choice中存储了一个字符串。否则,您可以假定发生了故障。

您有什么问题?你发布了一堆代码,但不是问题所在。此外,如果失败,返回-1应该是返回1。要返回的有效值为0到255。很抱歉,这是我在尝试编译和链接时出错的:friends。c:23:错误:分配中不兼容的类型也感谢关于-1的问题。当您扫描字符串%s时,不包括符号&就在变量名之前是的,我刚刚发送了输出,我看到了,所以我猜我必须验证是否有输入,然后通过这种方式发送?