字符串输入不起作用.... [英] String input not working....

查看:143
本文介绍了字符串输入不起作用....的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算输入是pallindrome numbre或不...我的代码适用于第一个输入但它崩溃后....请帮助... ...无法理解..



我的尝试:



i am trying to calculate the input is pallindrome numbre or not...my code works for the first input but it crashes after it....help please...cann't understand..

What I have tried:

#include <iostream>
#include
using namespace std;

int main()
{
//    ios_base ::sync_with_stdio(0);
//    cin.tie(0);
    int n;
    while(scanf("%d",&n)==1)
    {
        for(int i=0; i<n;>        {
            string s;
            //long long number;
            scanf("%s",&s);
            //cin>>s;
            int cnt=s.size();       //program cann't calculate the string
            int k=0,check=0;        // size here for the second input
            int j=cnt-1;
            cout<<"Case "<<i+1<<": ";
            while(k<=cnt/2)
            {
                if(s[k]==s[j])
                {
                    k++;
                    j--;
                }
                else
                {
                    check=1;
                    break;
                }
            }
//            if(numbe==1)
//                cnt++;
            if(check==1)
                cout<<"No\n";
            else
                cout<<"Yes\n";
        }
    }
    // cout << "Hello world!" << endl;
    return 0;
}</iostream>

推荐答案

此代码部分不起作用:

This code part won't work:
string s;
scanf("%s",&s);



std :: string 类不支持直接写入内部缓冲区。即使它支持你必须首先设置字符串的最大大小(分配内存)。



你可以使用 getline(string) - C ++参考 [ ^ ]从 std :: cin 中读取控制台输入(参见示例代码)在上面的链接)。或者使用足够大小的 char wchar_t 缓冲区(类型取决于您的操作系统和Unicode设置):


The std::string class does not support direct writing to the internal buffers. Even if it would support that you would have to set the maximum size of the the string first (allocate the memory).

You may use getline (string) - C++ Reference[^] instead to read console input from std::cin (see example code in the above link). Alternatively use a char or wchar_t buffer with sufficient size (type depends on your OS and Unicode setting):

// Adjust this according to your needs
#define MAX_INPUT_STR_LEN 80
// ...
char buffer[MAX_INPUT_STR_LEN + 1];
// Specify MAX_INPUT_STR_LEN value here to avoid buffer overflows 
scanf("%80s", buffer);
s = buffer;


这是一个简单的错误,它将本机数据类型与高级别对象不匹配。您必须通过提供字符缓冲区和字符串对象来严格使用 scanf



it is a simple bug by mismatching a native data type with a high level object. You must use scanf rigthtly by providing a char buffer and not a string object.

char buff[20]={};//must be big enough
scanf("%s",buff);//scan pure chars in buff
s = buff;//assign to string





学习并理解基础知识;-)



BTW:编译器没有警告?



Learn und understand the fundamentals ;-)

BTW: wasnt there a warning from the compiler?


这篇关于字符串输入不起作用....的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆