我试图从输入文件中创建令牌。因此,我得到一行fgets并将其提供给一个辅助方法,该方法接收一个char *并返回该标记的char *。我正在使用strtok()和分隔符作为" "因为代币都被" &#34 ;.但是,我无法弄清楚为什么代码每行只产生2个令牌而只是移动到下一行,即使该行中有更多需要被标记化。这是代码:
package keepo;
import java.awt.Rectangle;
public class tuna{
public static void main(String [] args){
Rectangle rect = new Rectangle(10,20,50,40);
double area,width,height;
width = rect.getWidth();
height = rect.getHeight();
area = width * height;
System.out.println("Width is : " + width + "Height is : " + height);
System.out.println("Area is : " + area);
}
}
以下是我在主方法中存储令牌的方法:
char *TKGetNextToken( char * start ) {
/* fill in your code here */
printf("Entered TKGetNextToken \n");
printf(&start[0]);
char* temp = &start[0];
//Delimiters for the tokens
const char* delim = " ";
//store tempToken
char* tempTok = strtok(temp, delim);
//return the token
return tempTok;
}
所以,假设我有一个file.txt:
//call get next token and get the token and store into temptok
while (temp!= NULL) {
tempTok = TKGetNextToken(temp);
printf("tempTok: %s\n",tempTok);
token.charPtr[tempNum] = tempTok;
tempNum++;
printf("Temp: %s\n",tempTok);
temp = strtok(NULL, " \0\n");
}
创建的令牌将是" abcd"和" ef"并且它将继续到下一行而不用为#34; ghij"和" asf32"。
答案 0 :(得分:2)
使用strtok
char *tempTok = strtok(line, " "); //initialize
while (tempTok != NULL) {
//do the work
tempTok = strtok(NULL, " \n"); //update
}
如果您喜欢上述内容,那么您可以轻松获得令牌。请查看此示例,该示例与您的代码类似,只记得您如何正确使用strtok
,然后它才能正常工作。查看strtok
以及如何在循环中使用它,更新并使用char *
。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *fp = fopen("data.txt", "r");
char line[256];
while (fgets(line, sizeof(line), fp)) {
char *tempTok = strtok(line, " ");
while (tempTok != NULL) {
printf("token %s\n", tempTok);
tempTok = strtok(NULL, " \n");
}
}
fclose(fp);
return 0;
}
文件data.txt
abcd ef ghij asf32
fsadf ads adf
输出
./a.out
token abcd
token ef
token ghij
token asf32
token fsadf
token ads
token adf