向链表添加空格

时间:2016-04-28 06:20:45

标签: c++ string c++11

过去几天,我一直在撞墙,想弄清楚如何在读取文件后为输出添加空间。代码从文件读取并输出到控制台“Ilikecomputers”,当它应该打印出“我喜欢计算机”时。有关如何添加空间的任何提示?

谢谢

代码在

之下
#include <iostream>
#include <list>
#include <ctype.h>
#include <fstream>

using namespace std;

void printList(const list<char> &myList);
void fillList(list<char> &myList);
void changeCase(list <char> &myList);

void printList(const list<char> &myList)
{
   list<char>::const_iterator itr;
   cout << "\nAfter Conversion: " << endl;
   for (itr = myList.begin(); itr != myList.end(); itr++ ) {
   cout <<*itr;
}
cout << '\n';
}

void fillList(list<char> &myList)
{
ifstream file("test.txt");
    string print;
    while(file >> print){
    for (int i = 0; i<print.length(); i++) {
    myList.push_back(print[i]);
  }
 }
}

int main ()
{
  list<char> myList;

  cout << "Before Conversion: " << endl;
  ifstream file("test.txt");
  string print;
  while(file >> print){    
  cout << print << " ";
 }

  fillList(myList);
  printList(myList);

 return 0;
}

2 个答案:

答案 0 :(得分:1)

在阅读时,您需要指定std::noskipws,否则>>会跳过空格和其他空白字符。只需要把

file >> std::noskipws;

在阅读之前。

答案 1 :(得分:0)

你可以这样做:

void fillList(list<char> &myList)
{
  ifstream file("test.txt");
  string print;
  while(file >> print){
    for (int i = 0; i<print.length(); i++) {
      myList.push_back(print[i]);
    }
    myList.push_back(' '); // this is what you were missing
  }
}

或者您可以逐个读取字符并插入所有字符,而不是像operator >>那样隐式地跳过空格。

相关问题