我正在编写允许用户输入句子的代码。程序将打印出第三个单词的句子。例如:
Enter a sentence: Welcome to the world of code
the world of code
Go again(y/n)? y
我已经实现了使用FOR循环执行此代码的操作,但是,因为我正在尝试学习这种令人困惑的指针云,因此我想INSTEAD使用单独的char
指针来指向句子的第三个单词,并使用该指针来创建输出(打印)。
我曾尝试寻找类似的代码/教程来解释这种情况下的指针,但是由于某种原因,我很难理解它们,否则它们将无法解释我的问题的解决方案。
所以,问题来了:我如何(而不是for循环,或同时使用两个(?)),将指针(例如char *
)附加到句子中的第三个单词并打印出来?
我当前的代码:
#include <stdio.h>
void main()
{
char str[100];
char* new_ptr = (char*)str;
int count = 0;
printf("Enter any string: ");
gets(str);
for (; *new_ptr && count < 3; new_ptr++)
if (*new_ptr == ' ')
count++;
printf(": %s", new_ptr);
if (count < 3) {
printf("Input needs more spaces!");
}
}
它还没有用于重新启动程序的循环,我将在以后修复。
如果有其他问题,请随时批评代码!
展开@EOF的评论:
您的main()
应该返回整数,因为返回值指示程序是否成功运行。 (0 ==成功)
也应使用fgets()
而不是gets()
。 gets()
不再是stdio.h
的一部分(自从我认为C11以来就没有),因为它不能防止缓冲区溢出。
您可以使用的功能:
void print_after_three(void)
{
const char delim[] = " ";
char str[100];
char *token;
int flag = 0;
printf("Enter any string: ");
fgets(str, 100, stdin);
/* Parses str to smaller strings */
token = strtok(str, delim);
while (token != NULL)
{
/* Print after 2 words */
if (++flag > 2)
printf("%s ", token);
token = strtok(NULL, delim);
}
if (flag < 3)
printf("Input needs more spaces!");
}
并查询用户是否要再次运行该功能:
int main(void)
{
char ch;
do
{
print_after_three();
printf("Go again(y/n)? ");
ch = getchar();
getchar();
} while (ch == 'y');
return 0;
}