我写了一个c ++代码来删除一个句子的空格,但是当我尝试打印它时,它不会打印出第一个单词

时间:2010-11-19 06:29:58

标签: c++ visual-c++

# include <iostream>
# include <ctime>

using namespace std;

int stripWhite(char *str);

int main ()
{

 char str[50];
 cout << "Enter a sentence . " << endl;
 cin >>str;
 cout << "Your sentence without spaces is : " << endl;
 cout << (str) << endl; // This is my problem. The sentence only prints the first word

 stripWhite(str);
 cout << "There were " << stripWhite(str) << " spaces." << endl;
 return 0;
}
int stripWhite(char *str)
{
 char *p = str;
 int count = 0;
 while (*p)
 {
  if (*p != ' ')
   count++;
  {
   *p++;
  }
 }
 return count;

4 个答案:

答案 0 :(得分:1)

std::cin将空格视为字符串指示符的结尾。

为了获得完整的句子,请使用std::getline。因为这需要std :: string作为其参数之一,所以你必须相应地调整stripWhite函数:

# include <iostream>
# include <string>

using namespace std;

int stripWhite(string str); //change the formal parameter's type

int main ()
{

 string str;
 cout << "Enter a sentence . " << endl;
 getline(cin, str,'\n'); //use getline to read everything that has been entered till the press of enter
 cout << "Your sentence without spaces is : " << endl;
 cout << (str) << endl; // This is my problem. The sentence only prints the first word

 stripWhite(str);
 cout << "There were " << stripWhite(str) << " spaces." << endl;
 system("pause");
 return 0;
}

int stripWhite(string str)
{

 int count = 0;
 char* p = str.c_str;
 while (*p)
 {
  if (*p != ' ')
   count++;
  {
   *p++;
  }
 }
 return count;
}   

答案 1 :(得分:1)

如果您不想用C ++字符串类型替换函数,可以使用cin.getline来获取c字符串(char数组)

cin.getline(str, 50);

答案 2 :(得分:0)

正如其他人所指出的,您应该使用std::getline代替cin >> str

但是,您提供的代码中还有其他一些问题。

  • 为什么在使用std::string时使用char数组?为什么你这么确定50个字符就足够了?
  • 您的stripWhite函数似乎没有删除任何内容:您计算非空格字符的数量,但实际上并没有删除任何内容。请注意,如果切换到std::string而不是char数组的普通,你可以使用标准算法来完成这项工作(在我的头顶,我想std::remove是合适的)
  • 假设stripWhite 确实实际修改了输入字符串,为什么要从主系统调用它?如果目标是首先剥离字符串,然后然后打印已删除空格的数量,请使stripWhite返回已删除空格的数量并将此结果存储在main中。< / LI>

例如:

const int nbSpacesStripped = stripWhite(str);
cout << "There were " << nbSpacesStripped << "spaces." << endl;

答案 3 :(得分:0)

看见Boost String Algorithms,尤其是replace/erase例程。

# include <iostream>
# include <string>

size_t stripWhiteSpaces(std::string& str)
{
  size_t const originalSize = str.size();
  boost::erase_all(str, ' ');
  return originalSize - str.size();
}

int main ()
{

  std::string str;
  std::cout << "Enter a sentence . \n";
  getline(std::cin, str);

  size_t const removed = stripWhiteSpaces(str);
  std::cout << "Your sentence without spaces is :\n";
  std::cout << (str) << '\n';

  std::cout << "There were " << removed << " spaces.\n";
  system("pause");
}