gpt4 book ai didi

c - 从标准输入读取字符串

转载 作者:太空宇宙 更新时间:2023-11-04 02:03:16 24 4
gpt4 key购买 nike

我正在尝试从标准输入读取一行,格式如下:

Boston "New York""San Francisco"Memphis(请注意,带空格的字符串位于方括号之间。另请注意,每个城市名称均由空格分隔。)我尝试一次用 scanf 读取一个,fgets 整行然后标记化,但结果不佳。我假装是将所有内容存储在一个多维字符数组中以备后用。

关于如何解决这个问题有什么建议吗?提前致谢!

最佳答案

您可以阅读整行内容并自己轻松地对其进行解析。如果您遇到的第一个非空白字符不是 ",则读取到下一个空格。如果是,则读取到下一个 ",假设您不需要担心转义引号。

这是一个简单的实现:

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

#define MAX_BUFFER 100
#define MAX_STRINGS 10

int main(void) {
char buffer[MAX_BUFFER];

if ( !fgets(buffer, MAX_BUFFER, stdin) ) {
fprintf(stderr, "Couldn't get input.\n");
return EXIT_FAILURE;
}
else {

/* Remove trailing newline, if present */

size_t length = strlen(buffer);
if ( length && buffer[length - 1] == '\n' ) {
buffer[length - 1] = '\0';
}
}

char *my_strings[MAX_STRINGS + 1] = {NULL};
int read_strings = 0;
char *buf_ptr = buffer;

while ( *buf_ptr && read_strings < MAX_STRINGS ) {
char temp_buf[MAX_BUFFER] = {0};
char *temp_ptr = temp_buf;

/* Skip leading whitespace */

while ( *buf_ptr && isspace(*buf_ptr) ) {
++buf_ptr;
}

if ( *buf_ptr ) {
if ( *buf_ptr == '"' ) {

/* If starts with '"', read to next '"'... */

++buf_ptr; /* Skip first " */
while ( *buf_ptr && *buf_ptr != '"' ) {
*temp_ptr++ = *buf_ptr++;
}

if ( *buf_ptr ) {
++buf_ptr; /* Skip second " */
}
}
else {

/* ...otherwise, read to next whitespace */

while ( *buf_ptr && !isspace(*buf_ptr) ) {
*temp_ptr++ = *buf_ptr++;
}
}

/* Copy substring into string array */

my_strings[read_strings] = malloc(strlen(temp_buf) + 1);
if ( !my_strings[read_strings] ) {
fprintf(stderr, "Couldn't allocate memory.\n");
return EXIT_FAILURE;
}
strcpy(my_strings[read_strings++], temp_buf);
}
}

for ( size_t i = 0; my_strings[i]; ++i ) {
printf("String %zu: %s\n", i + 1, my_strings[i]);
free(my_strings[i]);
}

return 0;
}

示例输出:

paul@MacBook:~/Documents/src/scratch$ ./ql
Boston "New York" "San Francisco" Memphis
String 1: Boston
String 2: New York
String 3: San Francisco
String 4: Memphis
paul@MacBook:~/Documents/src/scratch$ ./ql
a quoted "word" and "some quoted words" and an "unclosed quoted string
String 1: a
String 2: quoted
String 3: word
String 4: and
String 5: some quoted words
String 6: and
String 7: an
String 8: unclosed quoted string
paul@MacBook:~/Documents/src/scratch$

关于c - 从标准输入读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23963747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com