从getline中提取字符数组,不使用字符串
问题描述:
所以我想从文本文件中提取一行,并提取每行中的第一个字并保存在字符数组“op”中。我在处理第一个单词之前的空格时遇到了麻烦。文中的第一行是“真棒酱油”,第二行是“是”,第三行是“酷”,第四行是“是的好”。在单词yeah之前处理空格有困难。从getline中提取字符数组,不使用字符串
infile.open(“vec.txt”);
//define line pointer
char* line=new char[100];
char other[100];
char op[100];
int numofLines = 0;
int k = 0;
bool wordStart = false;
//get line
while (infile.getline(other,100))
{
int numofChar = k;
int numofOpChar = 0;
int r = 0;
int p = 0;
while (other[k] == ' ')
{
while (other[k] != ' ')
{
wordStart = true;
}
k++;
cout << k << endl;
}
if (wordStart = true)
{
do
{
op[numofOpChar] = other[numofChar];
numofChar++;
numofOpChar++;
}
while (other[numofChar] != ' ');
if (op[numofChar] != ' ')
{
cout << op << endl;
}
}
}
答
如果我理解正确的你所需要的是下面的。为了简单起见,我使用了std::stringstream
而不是文件。
#include <iostream>
#include <sstream>
#include <cstring>
#include <limits>
int main()
{
const size_t N = 100;
const char text[] = "awesome sauce\n" "yes\n" "cool\n" " yeah ok";
char line[N];
char op[N];
size_t pos = 0;
std::istringstream is(text);
while (is >> op)
{
is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << op << std::endl;
}
return 0;
}
程序输出是
awesome
yes
cool
yeah
答
ü应使用k开始串提取要连接所有的第一句话该文件以一个字符数组运算在
numofchar = k;
if (wordStart = true)
{
do
{
op[numofOpChar] = other[numofChar];
做什么? –
不,我希望操作码数组每次都包含第一个单词。 – ruchithelamp
德你用调试器通过代码?它出错了哪里? – pm100