【问题标题】:Extracting Char Array From getline, Without the Use of String从 getline 中提取字符数组,而不使用字符串
【发布时间】:2016-11-20 22:09:42
【问题描述】:

所以我想从文本文件中获取行,并提取每行中的第一个单词并保存在字符数组“op”中。我在处理第一个单词之前的空格时遇到了麻烦。文本中的第一行是“awesome sauce”,第二行是“yes”,第三行是“cool”,第四行是“yeah ok ”。处理单词yes之前的空格时遇到问题。

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; 
        }

    }

}

【问题讨论】:

  • 是否要将文件中的所有第一个单词连接到一个字符数组 op 中?
  • 不,我希望操作码数组在每个实例中每次都包含第一个单词。
  • 您是否使用调试器单步执行代码?哪里出错了?

标签: c++ arrays parsing char text-extraction


【解决方案1】:

如果我对您的理解正确,您需要的是以下内容。为简单起见,我使用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

【讨论】:

    【解决方案2】:

    你应该使用 k 开始字符串提取

    numofchar = k;
    if (wordStart = true)
    {
        do
        {
            op[numofOpChar] = other[numofChar]; 
    

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-22
      • 1970-01-01
      • 1970-01-01
      • 2013-09-19
      相关资源
      最近更新 更多