如何创建一个由从文本文件中读取的字符组成的字符串?

时间:2013-10-06 09:20:49

标签: c++ string char

我正在尝试读取代码并对其进行格式化,以便切断并在某个点之后转到新行。起初,我试图简单地继续显示连续的字符,并在该点读取的字符数量超过限制后使其进入换行符。但是,如果单词超过限制,我需要让该单词开始新行。由于我完全不知道如何只使用字符,我决定尝试使用字符串数组。我的代码如下

char ch;
string words[999];
//I use 999 because I can not be sure how large the text file will be, but I doubt it   would be over 999 words
string wordscount[999];
//again, 999. wordscount will store how many characters are in the word
int wordnum = 0;
int currentnum = 0;
//this will be used later
while (documentIn.get(ch))
{
if (ch != ' ')
//this makes sure that the character being read isn't a space, as spaces are how we differentiate words from each other
{
cout << ch;
//this displays the character being read

在我的代码中,我希望将所有字符“保存”为字符串,直到字符为空格。我不知道该怎么做。有人可以帮我从这里出去吗?我认为它会是这样的;

words[wordnum] = 'however i add up the characters'
//assuming I would use a type of loop to keep adding characters until I reach a 
//space, I would also be using the ++currentnum command to keep track of how
//many characters are in the word
wordscount[wordnum] = currentnum;
++wordnum;

2 个答案:

答案 0 :(得分:0)

使用输入文件流循环将这些单词添加到向量中,然后vector.size()将是单词count。

std::ifstream ifs("myfile.txt");

std::vector<std::string> words;
std::string word;
while (ifs >> word)
   words.push_back(word);

默认情况下将跳过空格,while循环将继续,直到到达文件末尾。

答案 1 :(得分:0)

我不知道你真正想做什么。

如果要从文件中恢复每一行,可以这样做:

std::ifstream ifs("in");
std::vector<std::string> words;
std::string word;
while (std::getline(ifs, word))
{
    words.push_back(word);
}
ifs.close();

函数std :: getline()将不会使用空格,例如'','\ t',而将通过ifs&gt;&gt;进行预测。字。