简体   繁体   中英

C++: strtok strange behaviour in last element of the line of input file?

I am reading from a file (sample shown below), line by line, and for each line I use strtok to get the elements which are divided by tabs (as shown in the code). Now, when I create the file with the data, I do this: type "A", type tab, type "10" press enter , and so on. In this case, when the number is printed, it is followed by strange characters, and sometimes letters/numbers. "A patch" for this problem would be to enter the data in the following way: type "A", press tab, type "10" press tab . Can anyone explain to me why this is happening, and is there a better way to fix it?

sample.txt

 A    10
 B    20
 C    30 

 //str contains a line of the file           
 char * pch = strtok (str,"\t");
 //print character
 if(pch !=NULL){
    cout<<pch<<endl;
 }
 //print number
 pch = strtok (NULL, "\t");
 if(pch !=NULL){
    cout<<pch<<endl;
 }

我不知道问题的原因是什么,但是我通过从文件读取的每一行的末尾添加了制表符(“ \\ t”)来“修复”该问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM