我想从stdin中读取一个字符串,将其保存在数组中,然后进行转换,使其与特定的测试相匹配:
expected = "45 76 65 72 79 20"
自周五以来,我已经尝试了所有可以找到的解决方案,除了strtol
,我不知道如何使用。
char input;
char *buffer = NULL;
char chunk[2];
size_t stringLength = 0;
int n = 0;
while(fgets(chunk, 2, stdin) != NULL){
stringLength += strlen(chunk);
}
rewind(stdin);
buffer = (char *) malloc(stringLength + 1);
if (buffer == NULL)
exit(EXIT_FAILURE);
while(scanf("%c", &input) == 1) {
snprintf(buffer+n, 2, "%c", input);
n += strlen(chunk);
}
//code to convert char array buffer to array of hex separated by spaces
示例文本已从标准输入= "Every P";
中撤消
我需要输出以通过示例测试的字符串:= "45 76 65 72 79 20 50";
如果我有任何错误,请告诉我,我一直在学习如何编写C代码1 1/2个月。
谢谢!
答案 0 :(得分:1)
AFAIK,rewind(stdin)
值得怀疑。另一种选择是使用realloc
一次将数组增加一个字符。
int c;
char *s = NULL;
int char_count = 0;
// Read one char at a time, ignoring new line
while (EOF != (c = getc(stdin))) {
// Ignore CR (i.e. Windows)
if ('\r' == c) continue;
// Consume the newline but don't add to buffer
if ('\n' == c) break;
// Grow array by 1 char (acts like malloc if pointer is NULL)
s = realloc(s, ++char_count);
// TODO handle error if (s == NULL)
// Append to array
s[char_count - 1] = (char)c;
}
// Create the buffer for the hex string
// 3 chars for each letter -> 2 chars for hex + 1 for space
// First one does not get a space but we can use the extra +1 for \0
char *hex = malloc(char_count * 3);
// TODO handle error if (hex == NULL)
// Create a temporary pointer that we can increment while "hex" remains unchanged
char *temp = hex;
for (int i = 0; i < char_count; i++) {
// No space on first char
if (i == 0) {
sprintf(temp, "%02X", s[i]);
temp += 2;
}
else {
sprintf(temp, " %02X", s[i]);
temp += 3;
}
}
*temp = '\0';
printf("%s\n", hex);
// Cleanup
free(s);
free(hex);
输入:Every P
输出:45 76 65 72 79 20 50
如果您只想将stdin
复制为十六进制,则根本不需要任何缓冲区:
int c;
int char_count = 0;
// Read one char at a time and print as hex
while (EOF != (c = getc(stdin))) {
// No space on first char
if (0 == char_count++) {
printf("%02X", c);
}
else {
printf(" %02X", c);
}
}
puts(""); // If you need a newline at the end