C++ 为什么这个程序跳过循环?
我想不出这个程序有什么问题C++ 为什么这个程序跳过循环?,c++,string,C++,String,我想不出这个程序有什么问题 #include <iostream> using namespace std; int main(){ int t; char s[5]; cin>>t; cin>>s; while(t--){ char f[100]; cin>>f; cout<<f<<endl; } retur
#include <iostream>
using namespace std;
int main(){
int t;
char s[5];
cin>>t;
cin>>s;
while(t--){
char f[100];
cin>>f;
cout<<f<<endl;
}
return 0;
}
#包括
使用名称空间std;
int main(){
int t;
chars[5];
cin>>t;
cin>>s;
而(t--){
charf[100];
cin>>f;
cout考虑到终止的空字符,5个字符的字符串太长,无法放入字符[5];
。在这种情况下,t
似乎恰好位于内存中的s
之后,并且您的机器正在使用little endian,因此值为0的终止空字符被覆盖到t
的最小字节,t
的值恰好为零
为了避免这种情况,您应该使用std::string
而不是像这样使用char
数组:
#include <iostream>
#include <string>
using namespace std;
int main(){
int t;
string s;
cin>>t;
cin>>s;
while(t--){
string f;
cin>>f;
cout<<f<<endl;
}
return 0;
}
#包括
#包括
使用名称空间std;
int main(){
int t;
字符串s;
cin>>t;
cin>>s;
而(t--){
字符串f;
cin>>f;
对于读取字符数组,getline
通常更好,因为它需要一个长度参数。当字符串长度为时,您可以提供输出@mikecatCan
#include <iostream>
#include <string>
using namespace std;
int main(){
int t;
string s;
cin>>t;
cin>>s;
while(t--){
string f;
cin>>f;
cout<<f<<endl;
}
return 0;
}