我已经将这个函数解决了导致问题的原因,但是我会试着给这个问题提供足够的上下文,而不会让你仔细阅读文本的行和行:
基本上,我在下面的函数中输入一个字符串,如果字符串中的第一个字符是#,那么我想打印字符串.而已.
但是,执行此操作时,打印的字符串将以三个字符的长度剪切.例如,在输入字符串为" #Hello,World! "的情况下,仅打印" #H ".
我从以下输入文件中使用fgets()获取输入字符串:
#测试
########
更多
输出如下:
#Ť
###
###
#
#m的
以下是相关的修剪功能:
int main(int argc,char *argv[]){
FILE *input;
lineResponse response;
//If a filename was specified, the file exists, and it is openable
if(argv[1] != NULL && (input = fopen(argv[1],"r")) != NULL){
char *currentLine = "";
//Loop through the lines
while(fgets(currentLine,sizeof(input),input)){
response = parseLine(currentLine);
}
}
fclose(input);
getchar();
}
lineResponse parseLine(char *line){
lineResponse response = {0,NULL}; //0 is the default lineType, denoting a line that cannot be parsed
if(line != NULL){
if(line[0] == '#'){
printf("%s\n",line);
}
}
return response;
}
Run Code Online (Sandbox Code Playgroud)
lineResponse返回与此问题无关.什么可能导致修剪?如果您需要更广泛的示例,我可以提供一个.
char *currentLine = "";
//Loop through the lines
while(fgets(currentLine,sizeof(input),input)){
Run Code Online (Sandbox Code Playgroud)
这是你的问题.您正在声明一个char指针并为其指定一个字符串文字...然后尝试读入它.你似乎也不理解第二个论点fgets; 它读取的字符少于该字符数,并用a终止缓冲区\0.另请注意,换行符存储在缓冲区中,如果您不想要它们,则需要将其删除.
这应该是:
char currentLine[1024]; /* arbitrary - needs to be big enough to hold your line */
while(fgets(currentLine,1024,input)) {
Run Code Online (Sandbox Code Playgroud)
字符串文字(例如char* = "This is a string literal")是不可变的(只读).它们是在编译时创建的.
| 归档时间: |
|
| 查看次数: |
261 次 |
| 最近记录: |