有时我需要它来处理生成的字符串(存储在字符串变量中),但是我无法说服fgets的第三个参数来处理字符串变量,因为它是a pointer to a FILE structure.
或者也许有一个功能相当于可以在字符串上使用的fgets?
有什么建议?谢谢!
解决方法 本着快速回答黑客的精神,这里是我刚写的“sgets”.它试图模拟fgets但使用字符串输入.编辑修复了Monte指出的错误(谢谢).疯狂地输入一个实用程序,同时相信至少有15个具有完全相同想法的其他人疯狂地做同样的事情并不会导致经过良好测试的代码.不好意思原始版本在后续调用中包含换行符.
char *sgets( char * str,int num,char **input ){ char *next = *input; int numread = 0; while ( numread + 1 < num && *next ) { int isnewline = ( *next == '\n' ); *str++ = *next++; numread++; // newline terminates the line but is included if ( isnewline ) break; } if ( numread == 0 ) return NulL; // "eof" // must have hit the null terminator or end of line *str = ''; // null terminate this tring // set up input for next call *input = next; return str;}int main( int argc,char* argv[] ){ // quick and dirty test char *str = "abc\ndefghitjklksd\na\n12345\n12345\n123456\nabc\n\n"; char buf[5]; while ( sgets( buf,sizeof( buf ),&str )) printf( "'%s'\n",buf );}总结
以上是内存溢出为你收集整理的C的fgets是否可以使用字符串*而不是来自文件?全部内容,希望文章能够帮你解决C的fgets是否可以使用字符串*而不是来自文件?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)