如何查找空格并存储到变量中
How to find whitespace and store into variable?
在这个程序中,我试图找到数组的空白,并将该值存储到一个变量中,然后打印出该变量。我知道使用的唯一函数是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;}
每个窄字符分类函数都采用非负值或特殊值EOF
的int
参数。否则,行为是未定义的。对于大多数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;
}
相关文章:
- 存储变量的更有效方法是什么?
- 使用 system() 不存储变量C++?
- 在递归DP中,通过存储变量来分解递归调用:效率低下
- 使用 LDAP 存储C++变量
- 在满足特定条件时运行迭代C++以存储变量
- 使用getline解析和存储变量
- 如何存储变量的地址并使用指针打印值
- C++ / Objective-C++ - 如何在 NSDictionary 中存储C++变量?
- 如何从文件中读取并存储变量
- 指针是否延长了自动存储变量的生存期
- 如何在 INI、CFG 或 XML 文件中存储C++变量
- 如何在 c++ 中的字符串数组中存储变量
- 如何在特定偏移量处存储变量
- 如何存储变量的前一个值并更新它以进行比较
- 存储变量的有效方法是什么?(自制虚拟机)
- 在C++中存储变量
- 在c++中按值调用时,存储变量的副本
- 为什么lambda只捕获自动存储变量
- 如何在寄存器中存储c++变量
- Getline()结合cin.ignore()不存储变量?(错误)