从输入文件中逐行输入并使用 strtok() 进行标记化,并将输出放入输出文件中
我想做的是逐行输入文件并标记并输出到输出文件中。我能够做的是输入文件中的第一行,但我的问题是我无法输入下一行行标记化,以便可以将其保存为输出文件中的第二行,这是我迄今为止在输入文件中第一行时可以做的事情。
#include <iostream>
#include<string> //string library
#include<fstream> //I/O stream input and output library
using namespace std;
const int MAX=300; //intialization a constant called MAX for line length
int main()
{
ifstream in; //delcraing instream
ofstream out; //declaring outstream
char oneline[MAX]; //declaring character called oneline with a length MAX
in.open("infile.txt"); //open instream
out.open("outfile.txt"); //opens outstream
while(in)
{
in.getline(oneline,MAX); //get first line in instream
char *ptr; //Declaring a character pointer
ptr = strtok(oneline," ,");
//pointer scans first token in line and removes any delimiters
while(ptr!=NULL)
{
out<<ptr<<" "; //outputs file into copy file
ptr=strtok(NULL," ,");
//pointer moves to second token after first scan is over
}
}
in.close(); //closes in file
out.close(); //closes out file
return 0;
}
What I am trying to do is to input a file LINE BY LINE and tokenize and output into an output file.What I have been able to do is input the first line in the file but my problem is that i am unable to input the next line to tokenize so that it could be saved as a second line in the output file,this is what i could do so far fro inputing the first line in the file.
#include <iostream>
#include<string> //string library
#include<fstream> //I/O stream input and output library
using namespace std;
const int MAX=300; //intialization a constant called MAX for line length
int main()
{
ifstream in; //delcraing instream
ofstream out; //declaring outstream
char oneline[MAX]; //declaring character called oneline with a length MAX
in.open("infile.txt"); //open instream
out.open("outfile.txt"); //opens outstream
while(in)
{
in.getline(oneline,MAX); //get first line in instream
char *ptr; //Declaring a character pointer
ptr = strtok(oneline," ,");
//pointer scans first token in line and removes any delimiters
while(ptr!=NULL)
{
out<<ptr<<" "; //outputs file into copy file
ptr=strtok(NULL," ,");
//pointer moves to second token after first scan is over
}
}
in.close(); //closes in file
out.close(); //closes out file
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C++ 字符串工具包库 (StrTk) 针对您的问题提供了以下解决方案:
更多示例可以在此处找到
The C++ String Toolkit Library (StrTk) has the following solution to your problem:
More examples can be found Here
当 C++ 使这变得更简洁时,您正在使用 C 运行时库。
在 C++ 中执行此操作的代码:
输入:
输出:
如果需要换行符,请添加
out << endl;
在适当的点。You are using C runtime library when C++ makes this neater.
Code to do this in C++:
Input:
Output:
If you want newlines, add
out << endl;
at the appropriate point.