[英]How do I separate integers from a string and manipulate them in C?
I am scanning for a date in the format mm-dd-yyyy and I need to take out three ints and use them for multiple things. 我正在扫描格式为mm-dd-yyyy的日期,我需要取出三个整数并将它们用于多种用途。 How can I create three integers with mm dd and yyyy? 如何用dd和yyyy创建三个整数? Thanks! 谢谢!
Use the sscanf
call from <stdio.h>
. 使用来自<stdio.h>
的sscanf
调用。
char line[80];
int m, d, y;
fgets(fgets(line, sizeof line, stdin);
sscanf(line, "%d-%d-%d", &m, &d, &y);
It is better to use fgets+sscanf instead of scanf directly, because scanf has the notorious \\n
issue and does not check buffer lengths. 最好直接使用fgets + sscanf而不是scanf,因为scanf有一个臭名昭著的\\n
问题,并且不检查缓冲区长度。
Try this to use fgets for all input. 尝试使用fgets进行所有输入。
The do/while loops will continue until valid input is taken. do / while循环将继续进行,直到获得有效输入为止。
This only validates the month. 这仅验证月份。 Something should be added to verify day and year. 应该添加一些内容来验证日期和年份。
Check the return of sscanf to make sure the needed items have been successfully scanned. 检查sscanf的返回,以确保已成功扫描所需的项目。
#include <stdio.h>
int main(){
char line[100] = "";
int scanned = 0;
int valid = 0;
int mm = 0;
int dd = 0;
int yyyy = 0;
int x;
do {
printf("\n\t\t\t1) Input date (mm/dd/yyyy) to find days passed");
printf("\n\t\t\t2) Input passed days to find date in the year");
printf("\n\n\t\t\tYour choice (1/2): ");
if ( !( fgets ( line, sizeof line, stdin))) {
fprintf ( stderr, "problem getting input found EOF\n");
return 1;
}
if ( ( scanned = sscanf(line, "%d", &x)) != 1) {
valid = 0;
}
else {
if ( x == 1 || x == 2) {
valid = 1;
}
else {
valid = 0;
}
}
} while ( !valid);
if(x == 1) {
do {
printf ( "enter date mm-dd-yyyy\n");
if ( !( fgets ( line, sizeof line, stdin))) {
fprintf ( stderr, "problem getting input found EOF\n");
return 1;
}
if ( ( scanned = sscanf ( line, "%d-%d-%d", &mm, &dd, &yyyy)) != 3) {
valid = 0;
}
else {
valid = 1;
//validate the values for mm dd and yyyy
if ( mm < 1 || mm > 12) {
printf ( "invalid month try again\n");
valid = 0;
}
}
} while ( !valid);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.