如何查找空格并存储到变量中

How to find whitespace and store into variable?

本文关键字:存储 变量 空格 何查找 查找      更新时间:2023-10-16

在这个程序中,我试图找到数组的空白,并将该值存储到一个变量中,然后打印出该变量。我知道使用的唯一函数是isspace函数,当我使用它时,我收到的错误是:"isspace":无法将参数1从"char [80]"转换为"int"

任何帮助将不胜感激!

// Zachary Law Strings.cpp
#include <iostream>
using namespace std;
#include <string>
#include <iomanip>

int main()
{   int x, i,y;
char name[] = "Please enter your name: ";
char answer1 [80];
i=0;
y=0;
cout << name;
cin.getline(answer1, 79);
cout << endl;
x=strlen(answer1);
 for (int i = 0; i < x; i++){
    cout << answer1[i] << endl;
    if (isspace(answer1)) 
    {y=y+1;}}
 cout << endl << endl;
 cout << setw(80) << answer1;
 cout <<y;


return 0;}

每个窄字符分类函数都采用非负值或特殊值EOFint参数。否则,行为是未定义的。对于大多数C++实现,char是有符号类型,因此足够高的值(实际上是 ASCII 之外的所有字符)变为负值。

所以将参数投射到unsigned char,在添加相关索引后,

if( isspace( (unsigned char) answer1[i] ) )

然后,生成的非负值将被隐式转换为 int


与其在每次调用分类函数时都放置强制转换,不如考虑以更C++友好的方式包装它们,例如

auto is_space( char const c )
    -> bool
{ return ::isspace( (unsigned char) c ); }

请尝试以下操作:

for (int i = 0; i < x; i++){
    cout << answer1[i] << endl;
    if (isspace(answer1[i])) 
    {y=y+1;}}

正如我之前所说,您将数组而不是字符传递给isspace函数。

ISSPACE函数接受:int isspace ( int c );

/* isspace example */
#include <stdio.h>

#include <ctype.h>
int main ()
{
  char c;
  int i=0;
  char str[]="Example sentence to test isspacen";
  while (str[i])
  {
    c=str[i];
    if (isspace(c)) c='n';
    putchar (c);
    i++;
  }
  return 0;
}