Sha*_*awy 13 c++ string iostream tokenize visual-c++
我想要做的是输入一个文件LINE BY LINE并标记并输出到输出文件.我能够做的是输入文件中的第一行但我的问题是我无法输入下一行要标记化的行,以便它可以保存为输出文件中的第二行,这是我到目前为止输入文件中的第一行所能做的.
#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;
}
Run Code Online (Sandbox Code Playgroud)
小智 15
在C++字符串工具箱库(StrTk)具有以下问题的解决方案:
#include <iostream>
#include <string>
#include <deque>
#include "strtk.hpp"
int main()
{
std::deque<std::string> word_list;
strtk::for_each_line("data.txt",
[&word_list](const std::string& line)
{
const std::string delimiters = "\t\r\n ,,.;:'\""
"!@#$%^&*_-=+`~/\\"
"()[]{}<>";
strtk::parse(line,delimiters,word_list);
});
std::cout << strtk::join(" ",word_list) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
更多例子可以在这里找到
当 C++ 使这变得更简洁时,您正在使用 C 运行时库。
在 C++ 中执行此操作的代码:
ifstream in; //delcraing instream
ofstream out; //declaring outstream
string oneline;
in.open("infile.txt"); //open instream
out.open("outfile.txt"); //opens outstream
while(getline(in, oneline))
{
size_t begin(0);
size_t end;
do
{
end = oneline.find_first_of(" ,", begin);
//outputs file into copy file
out << oneline.substr(begin,
(end == string::npos ? oneline.size() : end) - begin) << ' ';
begin = end+1;
//pointer moves to second token after first scan is over
}
while (end != string::npos);
}
in.close(); //closes in file
out.close(); //closes out file
Run Code Online (Sandbox Code Playgroud)
输入:
一个,BC
德·FG·希吉克勒姆
输出:
abc 德 fg hijklmn
如果您需要换行符,请out << endl;在适当的位置添加。