不打印句子中前三个单词的指针

  • 本文关键字:三个 单词 指针 句子 打印 c
  • 更新时间 :
  • 英文 :


没有任何代码获取,我被困在如何解决这个问题上。 我希望代码让用户输入一个长句子,然后输入一个不打印任何给定句子前 3 个单词的指针。对我来说棘手的部分是字符在开始时没有定义,所以我不能只是删除我想要的单词。

考核:

您好,我需要帮助此代码

有关此代码的帮助

只需沿着这条线计算空格数

#include <stdio.h>
#define INPUT_BUFFER_SIZE 256
int main(void) {
// Reading user input
char buf[INPUT_BUFFER_SIZE];
fgets(buf, INPUT_BUFFER_SIZE, stdin);
int words_to_skip = 3;
char* current_pos = &buf[0];
for (; words_to_skip > 0 && *current_pos != 0; current_pos++) {
// If current char is space - then we reached the next word
if (*current_pos == ' ') {
words_to_skip--;
}
}
if (*current_pos == 0) {
printf("Not enough words enteredn");
} else {
printf("%s", current_pos);
}
}

或者,使用内置strchr()函数:

#include <stdio.h>
#include <string.h>
#define INPUT_BUFFER_SIZE 256
int main(void) {
// Reading user input
char buf[INPUT_BUFFER_SIZE];
fgets(buf, INPUT_BUFFER_SIZE, stdin);
int words_to_skip = 3;
char* current_pos = &buf[0];
while (current_pos != 0 && *current_pos != 0 && words_to_skip > 0) {
current_pos = strchr(current_pos, ' ');
if(current_pos != 0) {
current_pos++;
}
words_to_skip--;
}
if (current_pos == 0) {
printf("Not enough words enteredn");
} else {
printf("%sn", current_pos);
}
}