在我的C程序中,我有一個字符串,我希望一次處理一行,理想情況是將每行保存到另一個字符串中,按照所需字符串進行操作,然後重複。不過,我不知道這將如何實現。C - 如何逐行讀取字符串?
我正在考慮使用sscanf。 sscanf中是否存在「讀取指針」,就像我從文件中讀取一樣?這樣做會是另一種選擇嗎?
在我的C程序中,我有一個字符串,我希望一次處理一行,理想情況是將每行保存到另一個字符串中,按照所需字符串進行操作,然後重複。不過,我不知道這將如何實現。C - 如何逐行讀取字符串?
我正在考慮使用sscanf。 sscanf中是否存在「讀取指針」,就像我從文件中讀取一樣?這樣做會是另一種選擇嗎?
這裏是你如何能有效地做到這一點,如果你被允許寫入到長字符串的例子:
#include <stdio.h>
#include <string.h>
int main(int argc, char ** argv)
{
char longString[] = "This is a long string.\nIt has multiple lines of text in it.\nWe want to examine each of these lines separately.\nSo we will do that.";
char * curLine = longString;
while(curLine)
{
char * nextLine = strchr(curLine, '\n');
if (nextLine) *nextLine = '\0'; // temporarily terminate the current line
printf("curLine=[%s]\n", curLine);
if (nextLine) *nextLine = '\n'; // then restore newline-char, just to be tidy
curLine = nextLine ? (nextLine+1) : NULL;
}
return 0;
}
如果你不允許寫入的長字符串,然後你會需要爲每行創建一個臨時字符串,以便使每行字符串NUL終止。像這樣:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char ** argv)
{
const char longString[] = "This is a long string.\nIt has multiple lines of text in it.\nWe want to examine each of these lines separately.\nSo we will do that.";
const char * curLine = longString;
while(curLine)
{
const char * nextLine = strchr(curLine, '\n');
int curLineLen = nextLine ? (nextLine-curLine) : strlen(curLine);
char * tempStr = (char *) malloc(curLineLen+1);
if (tempStr)
{
memcpy(tempStr, curLine, curLineLen);
tempStr[curLineLen] = '\0'; // NUL-terminate!
printf("tempStr=[%s]\n", tempStr);
free(tempStr);
}
else printf("malloc() failed!?\n");
curLine = nextLine ? (nextLine+1) : NULL;
}
return 0;
}
你說'const char * headers'但是你正在修改字符(即使通過一個不同的指針)。不應該是const ... – mrbrdo
刪除了const標記。 –
'fgets()'也許? –
我可以使用fgets處理已存在的字符串嗎? – user1174511
我認爲以下幾點可能會回答你的問題: http://stackoverflow.com/questions/5597513/line-by-line-reading-in-c-and-c – Siva