Конкретная проблема, с которой вы сталкиваетесь, состоит в том, что строка формата scanf
в %f
пропускает пробел (, включая новые строки), пока не найдет фактический символ для сканирования. Из стандарта c99:
Спецификация преобразования выполняется в следующих шагах: & nbsp; & nbsp; - & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; Входные символы пробела (как указано в
blockquote>isspace
), если спецификация не включает спецификатор'['
,'c'
или'n'
.и в другом месте описывает
< blockquote>isspace()
:Стандартными символами пробела являются: пробел
blockquote>' '
, подача формы'\f'
, новая строка'\n'
, возврат каретки'\r'
, горизонтальная вкладка'\t'
и вертикальная вкладка'\v'
.Лучше всего использовать
fgets
для получения строки (и это можно легко защитить от переполнения буфера), а затем использоватьsscanf
в результирующей строке.Функция
scanf
является одной из тех, на которые вы должны смотреть очень осторожно. Следующий фрагмент кода - это тот, который я часто использую для обработки линейного ввода:#include <stdio.h> #include <string.h> #define OK 0 #define NO_INPUT 1 #define TOO_LONG 2 static int getLine (char *prmpt, char *buff, size_t sz) { int ch, extra; // Get line with buffer overrun protection. if (prmpt != NULL) { printf ("%s", prmpt); fflush (stdout); } if (fgets (buff, sz, stdin) == NULL) return NO_INPUT; // If it was too long, there'll be no newline. In that case, we flush // to end of line so that excess doesn't affect the next call. if (buff[strlen(buff)-1] != '\n') { extra = 0; while (((ch = getchar()) != '\n') && (ch != EOF)) extra = 1; return (extra == 1) ? TOO_LONG : OK; } // Otherwise remove newline and give string back to caller. buff[strlen(buff)-1] = '\0'; return OK; }
& nbsp;
// Test program for getLine(). int main (void) { int rc; char buff[10]; rc = getLine ("Enter string> ", buff, sizeof(buff)); if (rc == NO_INPUT) { // Extra NL since my system doesn't output that on EOF. printf ("\nNo input\n"); return 1; } if (rc == TOO_LONG) { printf ("Input too long [%s]\n", buff); return 1; } printf ("OK [%s]\n", buff); return 0; }
Тестирование его различными комбинациями:
pax> ./prog Enter string>[CTRL-D] No input pax> ./prog Enter string> a OK [a] pax> ./prog Enter string> hello OK [hello] pax> ./prog Enter string> hello there Input too long [hello the] pax> ./prog Enter string> i am pax OK [i am pax]
Я бы использовал эту функцию, чтобы безопасно получить строку, а затем просто используйте:
sscanf (buffer, "%f %f", &real, &img)
, чтобы получить фактические значения (и проверить количество).
На самом деле, вот полная программа, которая ближе к тому, что вы хотите:
#include <stdio.h> #include <string.h> #define OK 0 #define NO_INPUT 1 #define TOO_LONG 2 static int getLine (char *prmpt, char *buff, size_t sz) { int ch, extra; // Get line with buffer overrun protection. if (prmpt != NULL) { printf ("%s", prmpt); fflush (stdout); } if (fgets (buff, sz, stdin) == NULL) return NO_INPUT; // If it was too long, there'll be no newline. In that case, we flush // to end of line so that excess doesn't affect the next call. if (buff[strlen(buff)-1] != '\n') { extra = 0; while (((ch = getchar()) != '\n') && (ch != EOF)) extra = 1; return (extra == 1) ? TOO_LONG : OK; } // Otherwise remove newline and give string back to caller. buff[strlen(buff)-1] = '\0'; return OK; }
& nbsp;
int main (void) { int i = 1, rc; char prompt[50], buff[50]; float real, imag; while (1) { sprintf (prompt, "\nEnter real and imaginary for #%3d: ", i); rc = getLine (prompt, buff, sizeof(buff)); if (rc == NO_INPUT) break; if (*buff == '\0') break; if (rc == TOO_LONG) { printf ("** Input too long [%s]...\n", buff); } if (sscanf (buff, "%f %f", &real, &imag) == 2) { printf ("Values were %f and %f\n", real, imag); i++; } else { printf ("** Invalid input [%s]\n", buff); } } return 0; }
вместе с тестовым прогоном:
pax> ./testprog Enter real and imaginary for # 1: hello ** Invalid input [hello] Enter real and imaginary for # 1: hello there ** Invalid input [hello there] Enter real and imaginary for # 1: 1 ** Invalid input [1] Enter real and imaginary for # 1: 1.23 4.56 Values were 1.230000 and 4.560000 Enter real and imaginary for # 2: pax> _
Из http://www.c99.org/2010/01/23/writing-an-android-sync-provider-part- 1 / :
Первый фрагмент головоломки называется аутентификатором учетной записи, который определяет, как учетная запись пользователя будет отображаться в разделе «Аккаунты и синхронизация. ” настройки.Для реализации аутентификатора учетной записи требуется 3 части: служба , которая возвращает подкласс AbstractAccountAuthenticator из метода onBind, действие для запроса пользователю необходимо ввести свои учетные данные, и XML-файл, описывающий, как ваша учетная запись должна выглядеть при отображении для пользователя. Вам также потребуется добавить разрешение android.permission.AUTHENTICATE_ACCOUNTS в свой AndroidManifest.xml.