这是我目前掌握的C代码。我正在从输入文件中读取名字和姓氏,但给我带来麻烦的是打印出其他内容。
我不得不这样说:
Venus Jensen 33770530841邮箱:[email protected]邮箱:624-771-4676 SIJ SBE WHV TVW
把多余的东西移走让它变成这样:
维珍森维纳斯珍森(624)771-4676
我的问题是,我得到了正确的输出,但对于某些(1)没有FRNO或类似的东西,(2)没有@符号的行,该行仍然显示出来。例如,行:
诺伊·理查德974927158 [email protected] 079-651-3667 HAVQ
菲利普桑多瓦尔836145561普桑多夫卢埃杜奥克斯鲁697-728-1807 LHPN GUX
不应打印这些行,因为第一行没有等效的FRNO,第二行没有@符号。每次我试图添加要匹配但不保存的格式操作时,程序sscanf函数就开始出错。
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int main()
{
// Open the input file and print an error message if we're unsuccessful.
// (the error message is mostly to help you with debugging. We won't test
// this behavior).
FILE *fp = fopen("input.txt", "r");
char line[500];
if(!fp) {
printf("Can't open input file\n");
exit(1);
}
// Counting input lines, so we can report errors.
// Keep reading input lines until we reach the end-of-file.
// Write an output line or an error message for each one.
do {
int lineCount = 1;
char fName[12];
char lName[12];
//char skipNum[12];
char email[9];
//char firstNum[4];
//char secondNum[4];
//char thirdNum[5];
//printf("%c", ch);
char phone[] = "(123)123-1234";
//fscanf(fp, "%s", fName);
//fscanf(fp, "%s", lName);
//fscanf(fp, "%[1-9]", skipNum);
//fscanf(fp, "%[a-z]", email);
sscanf (line, "%11s%11s%*[ 0-9]%9[^@]%*[^0-9]%3c-%3c-%4c", lName, fName, email, &phone[1], &phone[5], &phone[9]);
//printf("Invalid line");
//printf("\n");
// exit(1);
printf("%s", line);
printf("\n");
printf("%s", email);
printf("%s", fName);
printf("%s", lName);
//printf("%s", skipNum);
//printf("%s", firstNum);
printf("%s", phone);
printf("\n");
lineCount++;
}
while (fgets(line, sizeof line, fp));
return EXIT_SUCCESS;
}
最佳答案
格式字符串"%20s%20s%*[ 0-9]%20[^@]@%*s%20s %3c-%3c-%4c"
%20s
将扫描多达20个非空白字符。忽略前导空白并在尾随空白处停止。%*[ 0-9]
将扫描空格和数字。星号*告诉sscanf放弃扫描的字符。%20[^@]@
将扫描多达20个字符,或在@
处停止扫描。然后它将尝试扫描@
。如果@
丢失,扫描将提前终止。%*s
将扫描非空白并丢弃字符。%20s
将扫描多达20个非空白字符。%3c
将忽略任何前导空格并扫描三个字符。-%3c
将扫描一个-
字符,然后扫描三个字符。如果-
丢失,扫描将提前终止。-%4c
将扫描一个-
字符,然后扫描四个字符。如果-
丢失,扫描将提前终止。
如果sscanf
不扫描七个项目,则不会打印任何内容。
#include <stdio.h>
#include <stdlib.h>
int main ( void) {
char line[500] = "";
int lineCount = 0;
FILE *fp = NULL;
if ( NULL == ( fp = fopen("input.txt", "r"))) {
fprintf( stderr, "Can't open input file\n");
exit(1);
}
while ( fgets ( line, sizeof line, fp)) {//read each line from the file
char fName[21];
char lName[21];
char match[21];
char email[21];
char phone[] = "(123)567-9012";
lineCount++;
if ( 7 == sscanf ( line, "%20s%20s%*[ 0-9]%20[^@]@%*s%20s %3c-%3c-%4c"
, lName, fName, email, match, &phone[1], &phone[5], &phone[9])) {
printf ( "line [%d] %s %s %s %s\n", lineCount, email, fName, lName, phone);
}
}
fclose ( fp);
return 0;
}
关于c - 如何从输入文件读取并保存每行的某些部分并将其输出到命令行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54601592/