【问题标题】:Reading in characters followed by numbers c++读入字符后跟数字c ++
【发布时间】:2016-10-12 21:38:33
【问题描述】:

所以我一直在网上寻找一种读取字符后跟数字的方法,到目前为止,每个人都在使用字符串函数。但是,我只被允许使用 C 风格的字符数组,当我读入文件时,我的程序遇到了问题。

我的文本文件是这样的:

23
11

Java 2 linux 3 fear 0 pool 2 do 0 red 1 lock. 1 I 0 random 2 computers, 0 not 0 the 0 open 2 car! 2 C, 0 lack 0 of 0 dog 1 green 2 C++ 0 bottle 2 wrong, 2 them. 0

5 1 10 21 9 6 21 11 13 16 20

到目前为止我的程序打印出来了:

11 23
Java 2

但是,我希望它打印出所有内容。有什么建议吗?这是我的代码

#include <iostream>
#include <fstream>

using namespace std;

struct pieces {

char word[5];
int jump;
} ;

 // Main Function
int main ()
{
// declare variables
int wordCount[2];
int keyCount[2];
int numKeys;
int numWords;
int keyAmount = 1;
int wordAmount = 23;
pieces cypher[wordAmount];
char filename[10];
ifstream inData;

  //prompt user for input file

cout << " Enter file name: ";
cin >> filename;

inData.open(filename);

if(inData.is_open());
{

    // read list of names into array

    for ( numKeys = numWords = 0; numKeys < keyAmount; numKeys++){

        inData >> wordCount[numKeys] >> keyCount[numKeys];

        for( numWords = 0; numWords < wordAmount; numWords++){

        inData >> cypher[numWords].word >> cypher[numWords].jump;

        }
    }



    // print out unsorted onto console

        for ( int i = 0; i < numKeys; ++i){
    cout << wordCount[i] << " ";
    cout << keyCount[i] << "\n";
    cout << cypher[i].word << " ";
    cout << cypher[i].jump << " ";



    }

}
inData.close();

  return 0;
}

【问题讨论】:

  • 使用动态调整大小的字符数组创建自己的string 类可能更简单,然后使用使用string 的解决方案之一
  • 你从哪里得到 keymount = 1?
  • @AndyG 那么我是否会在每次阅读单词时创建一个动态调整大小的字符数组?
  • @Raindrop7 如果我将该数字更改为其他任何数字,它只会继续打印数字,甚至不会打印一个字符。
  • 您想将单词存储在一个数组中,将数字存储在另一个数组中吗?

标签: c++ arrays text character


【解决方案1】:

您的阅读代码工作正常,但打印出cypher 内容的for 循环不正确。将其更改为此以查看文件中的所有内容:

for ( int i = 0; i < wordAmount; ++i){
    cout << cypher[i].word << " ";
    cout << cypher[i].jump << " ";

}

执行类似的for loop 2 次迭代以查看wordCountkeyCount 的内容。

【讨论】:

    【解决方案2】:

    我不知道您的目标是什么,但如果您只想将文本流式传输到控制台窗口并在文件中写入和格式化后打印,您可以使用 stdio.h 和 c 函数。

    尝试使用 fgetc();将符号读入 char 变量,然后是 printf();然后检查 fgetc() 何时为'',然后检查第二个符号以查看它是字母还是数字。如果是其中任何一个,则将您的计数器增加一个并等待另一个''。

    所以。等待 ' '。检查下一个符号。如果一个数字 d++;如果是符号 c++;等待下一个'';如果是 ' ' 再次等待。如果是数字,则在 d 中加 1,如果是符号,则在 c 中加 1。但这仅适用于实际单词。如果您的文件包含用 l33t 编写的单词,并且单词以 1amth3b3st 之类的数字开头。你的计数器会失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-22
      • 2015-02-17
      • 2015-09-08
      • 1970-01-01
      相关资源
      最近更新 更多