0

Example code:

    char cnumb1[2];
    NSLog(@"Do you have an account already?(1 for Yes, 0 for no)");
    int c;
    //Flushes input
    while((c = getchar()) != '\n' && c != EOF);
    fgets(cnumb1, sizeof cnumb1, stdin);
    size_t length = strlen(cnumb1);
    if (cnumb1 [length-1] == '\n'){ // In case that the input string has 1 character plus '\n'
        cnumb1 [length-1] = '\0';} // Plus '\0', the '\n' isn't added and the if condition is false.
    NSString* string = [NSString stringWithUTF8String: cnumb1];
    NSLog(@"string:%@", string);

With the input "0" (EDIT: For some reason, I need to press enter twice), I get the output "string:" As far as I can tell, the stdin isn't being set correctly. Also, the I started without the flush lines, but that caused lots of problems because I have more fgets later on and it the stdin would only be the initial input, so I added those.

Why isn't the input being set as stdin? Or is it another problem entirely?

4

1 回答 1

0

线

while((c = get char()) != '\n' && c != EOF);

需要直接在 fgets 之后,而不是之前。

另外,虽然不直接回答问题,但最好这样做

fgets(cnumb1, sizeof cnumb1, stdin);

然后在 sizeof cnumb1 中硬编码,正如@H2CO3 向我指出的那样。

于 2013-07-22T13:21:24.340 回答