cin >>给定字符串的int将int赋给0

时间:2018-10-22 08:33:38

标签: c++ cin

我遇到的问题是,如果您输入任何字符串,cin会将int赋值为0。一个有趣的发现是,如果您以后将cin赋给字符串,则会得到为int放入的整个字符串。 cin.fail()总是出于某些原因返回true,即使使用cin.ignore()等等,if(cin >> startingPosition)也总是返回true。因此,如何获得偶数识别符,它是字符串而不是int?如上所示,如果它是字符串,如何再次使其循环?

int getUserPosition(bool volatileCall = false) {
    cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
    int startingPosition;
    cin >> startingPosition;
    while (startingPosition >= WIDTH || startingPosition < 0) {
    cout << "Invalid slot." << endl << endl;

        if (volatileCall) {
            return -1;
        }
        cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
        cin >> startingPosition;
        cout << startingPosition << endl;

    }
    return startingPosition;
}

1 个答案:

答案 0 :(得分:0)

您必须保存cin的结果

import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.text.NumberFormat; import java.text.ParseException; import javax.swing.AbstractAction; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.DefaultCellEditor; import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.ScrollPaneConstants; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.border.MatteBorder; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; import javax.swing.text.MaskFormatter; public class VoucherDialog extends JDialog { JPanel contentPane; JLabel jl1,jl2,jl3; private JTable table; private JScrollPane scrollPane; DefaultTableModel model; String[] column_headers= {"SN","REF","DATE","PARTICULARS","AMOUNT",}; String[][] items= {}; Connection con=null; PreparedStatement pst=null; TableModel tm; ResultSet rs=null; String c1,c2; int rowz,col; JTextField snField,dateField,particularField,refField; JFormattedTextField amountField; JComboBox<String> ref_Cb; JPopupMenu popup; NumberFormat amountFormat; private double amount = 100000; /** * Launch the application. */ public static void main(String[] args) { try { VoucherDialog dialog = new VoucherDialog(); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } /** * Create the dialog. * @throws UnsupportedLookAndFeelException * @throws IllegalAccessException * @throws InstantiationException * @throws ClassNotFoundException * @throws ParseException */ public VoucherDialog() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException,NumberFormatException, ParseException { contentPane=new JPanel(); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); contentPane.setBackground(Color.WHITE); //setBounds(100, 100, 571, 322); setSize(Toolkit.getDefaultToolkit().getScreenSize()); setContentPane(contentPane); contentPane.setLayout(new BorderLayout(0, 0)); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); try { ActionListener a=new ActionListener(){ public void actionPerformed(ActionEvent ae) { dispose(); } }; this.getRootPane().registerKeyboardAction(a,KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0),JComponent.WHEN_IN_FOCUSED_WINDOW); } catch (Exception e) { e.printStackTrace(); } JPanel panel = new JPanel(); panel.setBorder(new MatteBorder(2, 2, 2, 2, (Color) new Color(0, 0, 0))); contentPane.add(panel, BorderLayout.NORTH); panel.setLayout(new GridLayout(6, 1, 0, 0)); jl1=new JLabel(); jl1.setHorizontalAlignment(SwingConstants.CENTER); jl1.setFont(new Font("Lucida Console", Font.BOLD, 16)); jl1.setText(c1); panel.add(jl1); jl2=new JLabel(); jl2.setHorizontalAlignment(SwingConstants.CENTER); jl2.setFont(new Font("Lucida Console", Font.PLAIN, 14)); jl2.setText(c2); panel.add(jl2); jl3=new JLabel(); jl3.setHorizontalAlignment(SwingConstants.CENTER); jl3.setFont(new Font("Lucida Console", Font.PLAIN, 16)); jl3.setText("**Product Master** "); panel.add(jl3); model=new DefaultTableModel(items,column_headers) { private static final long serialVersionUID = 1L; public boolean isCellEditable(int row, int column) { if(column == 0 ) return false; else return true; } }; table = new JTable(model){ // private boolean inLayout; @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); if (isRowSelected(row)) { c.setBackground(Color.WHITE); c.setForeground(Color.BLACK); } else { c.setBackground(Color.white); c.setForeground(Color.BLACK); } return c; } }; table.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent ke) { if(ke.getKeyCode() == KeyEvent.VK_ENTER) { // Select the current cell rowz = table.getSelectedRow(); col = table.getSelectedColumn(); int totalrows=table.getRowCount(); if((rowz+1)==totalrows) { model.addRow(new Object[] {"","","","",""}); } //table.repaint(); } if(ke.getKeyCode() == KeyEvent.VK_INSERT) { int row=table.getSelectedRow(); model.insertRow(row,new Object[] {"1","","","",""} ); } } @Override public void keyPressed(KeyEvent ke) { if(ke.getKeyCode() == KeyEvent.VK_ENTER) { // Select the current cell rowz = table.getSelectedRow(); col = table.getSelectedColumn(); int totalrows=table.getRowCount(); if((rowz+1)==totalrows) { for(int i=0;i<table.getColumnCount();i++) { int x=0; if(table.getSelectedRow()>0) { x=Integer.valueOf(table.getValueAt(table.getSelectedRow()-1,0).toString()); x=x+1; } else x=0; } } } } }); //to make the Border at selected cell table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,boolean hasFocus,int row,int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); //setBorder(noFocusBorder); if (hasFocus) { setBorder(new MatteBorder(2, 2, 2, 2, (Color) new Color(0, 0, 0))); // to scrolling JTable automatically to the Bottom scrollToVisible(table,table.getSelectedRow(),table.getSelectedColumn()); } return this; } }); table.setBackground(Color.WHITE); table.setShowVerticalLines(true); table.setShowHorizontalLines(false); // to work the enter key like the tab InputMap im = table.getInputMap(); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Action.NextCell"); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "Action.NextCell"); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "Action.NextCell"); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "Action.PreviousCell"); ActionMap am = table.getActionMap(); am.put("Action.NextCell", new NextCellActioin(table)); am.put("Action.PreviousCell", new PreviousCellAction(table)); //to remove the vertical lines of the Table Header for(int i = 0; i <column_headers.length; i++) { TableColumn column = table.getColumnModel().getColumn(i); column.setHeaderRenderer(new HeaderRenderer()); } table.setRowHeight(25); //table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); table.setFont(new Font("Lucida Console", Font.PLAIN, 18)); table.getTableHeader().setFont(new Font("Lucida Console", Font.BOLD, 16)); table.getColumnModel().getColumn(0).setMinWidth(50); table.getColumnModel().getColumn(0).setMaxWidth(50); table.getColumnModel().getColumn(1).setMinWidth(50); table.getColumnModel().getColumn(1).setMaxWidth(50); table.getColumnModel().getColumn(2).setMinWidth(130); table.getColumnModel().getColumn(2).setMaxWidth(130); table.getColumnModel().getColumn(3).setMinWidth(250); table.getColumnModel().getColumn(3).setMaxWidth(250); table.getColumnModel().getColumn(4).setMinWidth(250); table.getColumnModel().getColumn(4).setMaxWidth(250); TableColumn snColumn = table.getColumnModel().getColumn(0); snField=new JTextField(); snField.setBorder(new MatteBorder(2, 2, 2, 2, (Color) new Color(255, 0, 0))); snField.setFont(new Font("Lucida Console", Font.PLAIN, 18)); snColumn.setCellEditor(new DefaultCellEditor(snField)); TableColumn refColumn = table.getColumnModel().getColumn(1); refField=new JFormattedTextField(); refField.setFont(new Font("Lucida Console", Font.PLAIN, 18)); refField.setEditable(true); refField.setBorder(new MatteBorder(2, 2, 2, 2, (Color) new Color(255, 0, 0))); refColumn.setCellEditor(new DefaultCellEditor(refField)); TableColumn dateColumn = table.getColumnModel().getColumn(2); JFormattedTextField dateTextField = new JFormattedTextField(new MaskFormatter("##/##/####")); dateTextField.setFont(new Font("Lucida Console", Font.PLAIN, 18)); dateTextField.setBorder(new MatteBorder(2, 2, 2, 2, (Color) new Color(255, 0, 0))); dateColumn.setCellEditor(new DefaultCellEditor(dateTextField)); TableColumn particularColumn = table.getColumnModel().getColumn(3); particularField=new JTextField(); particularField.setBorder(new MatteBorder(2, 2, 2, 2, (Color) new Color(255, 0, 0))); particularField.setFont(new Font("Lucida Console", Font.PLAIN, 18)); particularColumn.setCellEditor(new DefaultCellEditor(particularField)); TableColumn amountColumn = table.getColumnModel().getColumn(4); //amountField=new JFormattedTextField(createAmountFormatter()); amountField=new JFormattedTextField(amountFormat); amountField.setValue(amount); //amountField.addFocusListener(l); amountField.setFont(new Font("Lucida Console", Font.PLAIN, 18)); amountField.setBorder(new MatteBorder(2, 2, 2, 2, (Color) new Color(255, 0, 0))); //amountField.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14)); amountColumn.setCellEditor(new DefaultCellEditor(amountField)); scrollPane=new JScrollPane(); scrollPane.setViewportBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(255, 0, 0))); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants. HORIZONTAL_SCROLLBAR_ALWAYS); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants. VERTICAL_SCROLLBAR_ALWAYS ); scrollPane.setViewportView(table); scrollPane.setForeground(Color.WHITE); table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF ); for(int i=0;i<=20;i++) { model.addRow(new Object[] {"1","","","",""}); table.setValueAt(i+1, i,0); } contentPane.add(scrollPane, BorderLayout.CENTER); } // to scrolling JTable automatically to the Bottom public static void scrollToVisible(final JTable table, final int rowIndex, final int vColIndex) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { table.scrollRectToVisible(table.getCellRect(rowIndex, vColIndex, false)); } }); } class NextCellActioin extends AbstractAction { private JTable table; public NextCellActioin(JTable table) { this.table = table; } public void actionPerformed(ActionEvent e) { int col = table.getSelectedColumn(); int row = table.getSelectedRow(); int colCount = table.getColumnCount(); int rowCount = table.getRowCount(); int x; System.out.println("NExt"); do { col++; if (col >= colCount) { col = 0; row++; } if (row >= rowCount) { row = 0; } TableColumn column = table.getColumnModel().getColumn(col); x=column.getWidth(); if(x!=0) col--; //else if(x==0) //setDefaultValue(col); }while(x==0); col++; if (col >= colCount) { col = 0; row++; } if (row >= rowCount) { row = 0; } table.getSelectionModel().setSelectionInterval(row, row); table.getColumnModel().getSelectionModel().setSelectionInterval(col, col); } } class PreviousCellAction extends AbstractAction { /** * */ private static final long serialVersionUID = 1L; private JTable table; public PreviousCellAction(JTable table) { this.table = table; } public void actionPerformed(ActionEvent e) { int col = table.getSelectedColumn(); int row = table.getSelectedRow(); int colCount = table.getColumnCount(); int rowCount = table.getRowCount(); System.out.println("Previous"); int x; do { col--; System.out.println("3"+col); if (col<0) { col =colCount-1; row--; System.out.println("1"+col); } if (row<0) { row =rowCount-1; } x = table.getColumnModel().getColumn(col).getWidth(); //x=column.getWidth(); if(x!=0) col++; //else if(x==0) System.out.println("2"+x); //setDefaultValue(col); }while(x==0); col--; if (col<0) { /*if (row==0) { row =rowCount; } else*/ System.out.println("2"+col); col =colCount-1; row--; System.out.println("3"+col); } if (row<0) { row =rowCount-1; } table.getSelectionModel().setSelectionInterval(row, row); table.getColumnModel().getSelectionModel().setSelectionInterval(col, col); } } } //this class used to hide the tableHeader class HeaderRenderer extends JLabel implements TableCellRenderer { /** * */ private static final long serialVersionUID = 1L; public Component getTableCellRendererComponent(JTable table, Object value, boolean hasFocus, boolean isSelected, int row, int col) { setText(value.toString()); setFont(new Font("Lucida Console", Font.PLAIN, 18)); setBorder(BorderFactory.createEmptyBorder(2,2,2,2)); return this; } }

整个代码看起来像

isNumber = (cin >> startPosition);