C控制台输入 我似乎无法谷歌,因为一切都变成了C++或C语言(边注:搜索C特定的任何简单方法)。我想弄清楚的是,如何接受控制台字符串输入,这样我就知道它的长度,这样我就可以通过使用for循环向后索引来以相反的顺序返回它。我过去有过一些C++经验,但从来没有真正使用过控制台IO。谢谢你的帮助 使用fgets()阅读 处理可能的尾随\n 找到长度
反向打印C控制台输入 我似乎无法谷歌,因为一切都变成了C++或C语言(边注:搜索C特定的任何简单方法)。我想弄清楚的是,如何接受控制台字符串输入,这样我就知道它的长度,这样我就可以通过使用for循环向后索引来以相反的顺序返回它。我过去有过一些C++经验,但从来没有真正使用过控制台IO。谢谢你的帮助 使用fgets()阅读 处理可能的尾随\n 找到长度,c,string,input,C,String,Input,反向打印 char buf[100]; if (fgets(buf, sizeof buf, stdin) == NULL) Handle_EOF(); buf[strcspn(buf, "\n")] = '\0'; // lop off potential trailing \n size_t len = strlen(buf); while (len) { putc(buf[--len], stdout); } 使用fgets()阅读 处理可能的尾随\n 找到长度 反向打印 cha
char buf[100];
if (fgets(buf, sizeof buf, stdin) == NULL) Handle_EOF();
buf[strcspn(buf, "\n")] = '\0'; // lop off potential trailing \n
size_t len = strlen(buf);
while (len) {
putc(buf[--len], stdout);
}
fgets()
阅读\n
char buf[100];
if (fgets(buf, sizeof buf, stdin) == NULL) Handle_EOF();
buf[strcspn(buf, "\n")] = '\0'; // lop off potential trailing \n
size_t len = strlen(buf);
while (len) {
putc(buf[--len], stdout);
}
您可以使用
fgets
功能读取标准输入
char buf[80];
if (fgets(buf, 80, stdin) != NULL)
/* buf now contains the first 80 chars of the input */
注意:请勿使用
gets
,因为这很危险,可能会使输入缓冲区溢出。您可以使用fgets
功能读取标准输入
char buf[80];
if (fgets(buf, 80, stdin) != NULL)
/* buf now contains the first 80 chars of the input */
注意:不要使用
gets
,因为这很危险——它会使输入缓冲区溢出。我编写此函数是为了将stdin中的输入放入缓冲区,用于uni中的cli项目
它逐字符读取stdin,没有缓冲区溢出
/*max line lenght*/
#define CLI_MAX_CMD_LEN 1024
/*get_line copies characters from stdin to buffer pointed by buf, stopping when a
carriage return or newline is encountered. It returns -1 on errors, otherwise strlen count */
int get_line(char *buf) {
int i,c;
for (i=0;i<CLI_MAX_CMD_LEN;i++) {
c = getchar();
switch (c) {
/*if terminating char is found an error has occurred*/
case '\0':
printf("found '\\0' instead of '\\n'\n");
return -1;
case '\t':
/*show possible commands*/
autocomplete(buf);
break;
case EOF:
/* prints the warning to stdout */
printf("End of file reached\n");
/* continue to execute following cases code */
case '\n':
case '\r':
buf[i] = '\0';
return i;
default :
buf[i] = c;
}
}
/*if end of buffer is reached put terminating char on last element
means that an error has occurred*/
buf[CLI_MAX_CMD_LEN] = '\0';
return -1;
}
/*最大线路长度*/
#定义CLI\u MAX\u CMD\u LEN 1024
/*get_行将字符从标准输入复制到buf指向的缓冲区,当
遇到回车符或换行符。错误时返回-1,否则返回strlen count*/
int get_行(字符*buf){
int i,c;
对于(i=0;i我编写此函数是为了将stdin的输入放入缓冲区,用于uni中的cli项目
它逐字符读取stdin,没有缓冲区溢出
/*max line lenght*/
#define CLI_MAX_CMD_LEN 1024
/*get_line copies characters from stdin to buffer pointed by buf, stopping when a
carriage return or newline is encountered. It returns -1 on errors, otherwise strlen count */
int get_line(char *buf) {
int i,c;
for (i=0;i<CLI_MAX_CMD_LEN;i++) {
c = getchar();
switch (c) {
/*if terminating char is found an error has occurred*/
case '\0':
printf("found '\\0' instead of '\\n'\n");
return -1;
case '\t':
/*show possible commands*/
autocomplete(buf);
break;
case EOF:
/* prints the warning to stdout */
printf("End of file reached\n");
/* continue to execute following cases code */
case '\n':
case '\r':
buf[i] = '\0';
return i;
default :
buf[i] = c;
}
}
/*if end of buffer is reached put terminating char on last element
means that an error has occurred*/
buf[CLI_MAX_CMD_LEN] = '\0';
return -1;
}
/*最大线路长度*/
#定义CLI\u MAX\u CMD\u LEN 1024
/*get_行将字符从标准输入复制到buf指向的缓冲区,当
遇到回车符或换行符。出错时返回-1,否则返回strlen count*/
int get_行(字符*buf){
int i,c;
对于(i=0;i这是我的解决方案,但使用递归:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 20
void reverseW(char *, int);
int main()
{
char tmp[N], *string;
printf("Type a String:\n");
scanf("%s", tmp);
string=(char*)malloc((strlen(tmp)+1)*sizeof(char));
if (string==NULL)
{
printf("Error !\n");
exit(0);
}
strcpy(string, tmp);
reverseW(string, strlen(string));
printf("\nThe reverse of %s is %s !\n", tmp, string);
free(string);
return 0;
}
void reverseW(char *word, int size)
{
char tmp;
if (size>1)
{
tmp=word[0];
word[0]=word[size-1];
word[size-1]=tmp;
reverseW(word+1, size-2);
}
return;
}
#包括
#包括
#包括
#定义n20
无效反转(字符*,整数);
int main()
{
字符tmp[N],*字符串;
printf(“键入字符串:\n”);
scanf(“%s”,tmp);
字符串=(char*)malloc((strlen(tmp)+1)*sizeof(char));
if(字符串==NULL)
{
printf(“错误!\n”);
出口(0);
}
strcpy(字符串,tmp);
反转(字符串,strlen(字符串));
printf(“\n%s的反面是%s!\n”,tmp,字符串);
自由(弦);
返回0;
}
void reverseW(字符*字,整数大小)
{
char-tmp;
如果(大小>1)
{
tmp=字[0];
字[0]=字[size-1];
字[size-1]=tmp;
反向(字+1,大小-2);
}
回来
}
这是我的解决方案,但使用递归:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 20
void reverseW(char *, int);
int main()
{
char tmp[N], *string;
printf("Type a String:\n");
scanf("%s", tmp);
string=(char*)malloc((strlen(tmp)+1)*sizeof(char));
if (string==NULL)
{
printf("Error !\n");
exit(0);
}
strcpy(string, tmp);
reverseW(string, strlen(string));
printf("\nThe reverse of %s is %s !\n", tmp, string);
free(string);
return 0;
}
void reverseW(char *word, int size)
{
char tmp;
if (size>1)
{
tmp=word[0];
word[0]=word[size-1];
word[size-1]=tmp;
reverseW(word+1, size-2);
}
return;
}
#包括
#包括
#包括
#定义n20
无效反转(字符*,整数);
int main()
{
字符tmp[N],*字符串;
printf(“键入字符串:\n”);
scanf(“%s”,tmp);
字符串=(char*)malloc((strlen(tmp)+1)*sizeof(char));
if(字符串==NULL)
{
printf(“错误!\n”);
出口(0);
}
strcpy(字符串,tmp);
反转(字符串,strlen(字符串));
printf(“\n%s的反面是%s!\n”,tmp,字符串);
自由(弦);
返回0;
}
void reverseW(字符*字,整数大小)
{
char-tmp;
如果(大小>1)
{
tmp=字[0];
字[0]=字[size-1];
字[size-1]=tmp;
反向(字+1,大小-2);
}
回来
}
您需要留出一些空间来存储输入;因为您事先不知道输入有多大,所以您必须对存储进行一些创新
一种常见的策略是使用一个较小的、固定大小的缓冲区来读取输入流,如果整个字符串的长度超过了固定大小的缓冲区所能处理的长度,则使用一个动态的、可调整大小的缓冲区来存储整个字符串。这样,您可以在离散块中读取任意长的输入行,然后将这些块粘贴在一起,从而调整字符串的大小如有必要,锁定缓冲区
您将在循环中从控制台读取固定大小的块,并将其存储到动态缓冲区,直到看到换行符,此时您将退出输入循环。理想情况下,固定大小的缓冲区应该足够大,以处理最合理的情况,这样您就不需要扩展动态缓冲区
过分冗长(未经测试!)示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INPUT_BUF_SIZE 21 // handle strings up to 20 characters in length
int main( void )
{
/**
* Set aside a fixed-size buffer to store input from the console. This
* buffer cannot be resized after it has been allocated.
*/
char inputBuf[INPUT_BUF_SIZE];
/**
* Dynamically allocate a buffer to store the final string;
* its initial size is the same as the fixed buffer. If necessary,
* this buffer may be extended with the realloc function. We're using
* calloc instead of malloc to make sure the initial array contents
* are set to 0.
*/
char *finalBuf = calloc( INPUT_BUF_SIZE, sizeof *finalBuf );
/**
* finalBufSize tracks the total size of the dynamic buffer; finalBufLen
* tracks the length of the string currently stored in the buffer.
* These are not the same thing.
*/
size_t finalBufSize = INPUT_BUF_SIZE;
size_t finalBufLen = 0; // initially no string stored in the buffer
/**
* Read from standard input into the fixed-size buffer; loop until
* we see EOF or there's an error on input.
*/
while ( fgets( inputBuf, sizeof inputBuf, stdin ) )
{
/**
* If there isn't enough space left in finalBuf to store
* the latest chunk, double the size of finalBuf. This strategy
* minimizes the number of times you have to call realloc (which
* can be expensive).
*/
if ( strlen( inputBuf ) + finalBufLen > finalBufSize )
{
/**
* *Always* assign the result of realloc to a temp variable; if the
* call fails it will return NULL, and if you overwrite the value
* of finalBuf with NULL, you'll lose your only reference to any
* previously allocated memory.
*/
char *tmp = realloc( finalBuf, finalBufSize * 2 );
if ( tmp )
{
finalBuf = tmp;
finalBufSize *= 2;
}
else
{
/**
* We can't extend the buffer anymore, so we'll exit the
* loop and work with what we have.
*/
fprintf( stderr, "Could not extend storage buffer, exiting input loop\n" );
break;
}
}
/**
* Append the input string to the target buffer.
*/
strcat( finalBuf, inputBuf );
finalBufLen = strlen( finalBuf );
/**
* Did we see a newline in the last input chunk? If so,
* remove that newline from the final string (unless you
* want to include that in your reversal) and exit
* the loop.
*/
char *newline = strchr( finalString, '\n' );
if ( newline )
{
*newline = 0; // overwrite the newline character with the string terminator
break;
}
}
理想情况下,您可以将所有输入处理分离到自己的函数中,但现在这是一个足够好的说明。您需要留出一些空间来存储输入;因为您事先不知道输入的大小,所以您必须对存储进行一些创新
一种常见的策略是使用一个较小的、固定大小的缓冲区来读取输入流,如果整个字符串的长度超过了固定大小的缓冲区所能处理的长度,则使用一个动态的、可调整大小的缓冲区来存储整个字符串。这样,您可以在离散块中读取任意长的输入行,然后将这些块粘贴在一起,从而调整字符串的大小如有必要,锁定缓冲区
您将在循环中从控制台读取固定大小的块,并将其存储到动态缓冲区,直到看到换行符,此时您将退出输入循环。理想情况下,固定大小的缓冲区应该足够大,以处理最合理的情况,这样您就不需要扩展动态缓冲区
过分冗长(未经测试!)示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INPUT_BUF_SIZE 21 // handle strings up to 20 characters in length
int main( void )
{
/**
* Set aside a fixed-size buffer to store input from the console. This
* buffer cannot be resized after it has been allocated.
*/
char inputBuf[INPUT_BUF_SIZE];
/**
* Dynamically allocate a buffer to store the final string;
* its initial size is the same as the fixed buffer. If necessary,
* this buffer may be extended with the realloc function. We're using
* calloc instead of malloc to make sure the initial array contents
* are set to 0.
*/
char *finalBuf = calloc( INPUT_BUF_SIZE, sizeof *finalBuf );
/**
* finalBufSize tracks the total size of the dynamic buffer; finalBufLen
* tracks the length of the string currently stored in the buffer.
* These are not the same thing.
*/
size_t finalBufSize = INPUT_BUF_SIZE;
size_t finalBufLen = 0; // initially no string stored in the buffer
/**
* Read from standard input into the fixed-size buffer; loop until
* we see EOF or there's an error on input.
*/
while ( fgets( inputBuf, sizeof inputBuf, stdin ) )
{
/**
* If there isn't enough space left in finalBuf to store
* the latest chunk, double the size of finalBuf. This strategy
* minimizes the number of times you have to call realloc (which
* can be expensive).
*/
if ( strlen( inputBuf ) + finalBufLen > finalBufSize )
{
/**
* *Always* assign the result of realloc to a temp variable; if the
* call fails it will return NULL, and if you overwrite the value
* of finalBuf with NULL, you'll lose your only reference to any
* previously allocated memory.
*/
char *tmp = realloc( finalBuf, finalBufSize * 2 );
if ( tmp )
{
finalBuf = tmp;
finalBufSize *= 2;
}
else
{
/**
* We can't extend the buffer anymore, so we'll exit the
* loop and work with what we have.
*/
fprintf( stderr, "Could not extend storage buffer, exiting input loop\n" );
break;
}
}
/**
* Append the input string to the target buffer.
*/
strcat( finalBuf, inputBuf );
finalBufLen = strlen( finalBuf );
/**
* Did we see a newline in the last input chunk? If so,
* remove that newline from the final string (unless you
* want to include that in your reversal) and exit
* the loop.
*/
char *newline = strchr( finalString, '\n' );
if ( newline )
{
*newline = 0; // overwrite the newline character with the string terminator
break;
}
}
理想情况下,您可以将所有输入处理分离到它自己的函数中,但现在这是一个足够好的说明。在搜索中使用标记来缩小结果范围,例如,搜索“[c]控制台输入”
fgets()
,然后搜索strlen()
是一个良好的开端。不管怎样,谷歌最热门的搜索结果很可能是StackOverflow我通常使用K&R的附录,其中列出了所有标准库函数。我还发现它相当可靠。POSIX具有getline函数,它似乎可以实现您想要的功能:如果缓冲区对于当前行太短,它会自动放大缓冲区。在搜索中使用标记来缩小结果范围,例如搜索“[c]控制台输入