C和c++中的字符串输入
String input in C and C++
我想用C或c++写一个程序,要求用户在运行时输入用户在不同时间给定的不同长度的字符串(空格分隔或非空格分隔),并将其存储到数组中。请给我C和c++的样例代码
。
1st run:
Enter string
Input: Foo
现在是char array[]="foo";
2nd run:
Enter string
Input:
Pool Of
现在char array[]="Pool Of";
I have try:
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"enter no. of chars in string";
cin>>n;
char *p=new char[n+1];
cout<<"enter the string"<<endl;
cin>>p;
cout<<p<<endl;
cout<<p;
return 0;
}
但是当字符串被空格分隔时,它不起作用
我也试过这个,但是它也不工作。
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"enter no. of chars in string";
cin>>n;
char *p=new char[n+1];
cout<<"enter the string"<<endl;
cin.getline(p,n);
cout<<p<<endl;
cout<<p;
return 0;
}
使用getline。
看一下这个例子:
http://www.cplusplus.com/reference/iostream/istream/getline/
您需要从stdin中读取字符,直到遇到某个结束符(例如换行符),并将该字符附加到临时字符数组(char*)的末尾。对于所有这些,您应该手动控制溢出并根据需要扩展(重新分配+复制)数组。
当您按下enter键时,您必须照顾额外的字符,该字符也馈送给cin.getline(),如果照顾到这一点,它将正常工作。这是cin在Windows中的行为。在Linux中也可能发生同样的情况。如果你在Windows中运行这段代码,它会给你你想要的。
#include <iostream>
using namespace std;
int main () {
int n;
// Take number of chars
cout<<"Number of chars in string: ";
cin>>n;
// Take the string in dynamic char array
char *pStr = new char[n+1];
cout<<"Enter your string: "<<endl;
// Feed extra char
char tCh;
cin.get(tCh);
// Store until newline
cin.getline(pStr, n+1);
cout<<"You entered: "<<pStr<<endl;
// Free memory like gentle-man
delete []pStr;
// Bye bye
return 0;
}
HTH !
相关文章:
- 如何使用堆栈将字符串输入拉伸 k 次
- 不确定出了什么问题(字符串输入)
- 如何获取字符串输入n次?
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- isPalindrome不显示输出,isPalindrome函数未使用字符串输入作为字符串参数进行测试
- C++ 对象数组字符串输入在控制台上不起作用
- 为什么 cin 在包含字符串标头后接受字符串输入
- 拆分字符串输入并查找字符是否有效
- 有没有办法将最初作为字符串输入的数字字符数组复制到双向链表中
- 将字符串输入到多维数组中
- 字符串输入后的空格
- 字符串流中的自定义字符串输入
- C 未验证字符串输入
- 总结数字字符串输入的最佳方法
- 如何验证用户将字符串输入到std :: cin中
- 在C++测试家庭作业问题中的字符串输入时无法退出循环(作为数据验证)
- 如何在C++中检测字符串输入中的换行符
- C++将字符串输入拆分为两个整数
- 如何检查字符串输入是否为有效的双精度
- 在读取数据文件时,如何找到用户字符串输入的字谜?